diff --git a/study-plan/algorithm/day-1/binary-search.rb b/study-plan/algorithm/day-1/binary-search.rb new file mode 100644 index 0000000..37103ef --- /dev/null +++ b/study-plan/algorithm/day-1/binary-search.rb @@ -0,0 +1,31 @@ +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer} +def search(nums, target) + left = 0 + right = nums.size + + while left < right do + mid = (left + right).div(2) + + if nums[mid] == target then + return mid + elsif nums[mid] < target then + left = mid + 1 + else + right = mid + end + end + + return -1 +end + +RSpec.describe "search" do + it "nums = [-1,0,3,5,9,12], target = 9" do + expect(search([-1,0,3,5,9,12], 9)).to eq(4) + end + + it "nums = [-1,0,3,5,9,12], target = 2" do + expect(search([-1,0,3,5,9,12], 2)).to eq(-1) + end +end diff --git a/study-plan/algorithm/day-1/first-bad-version.rb b/study-plan/algorithm/day-1/first-bad-version.rb new file mode 100644 index 0000000..60c33cf --- /dev/null +++ b/study-plan/algorithm/day-1/first-bad-version.rb @@ -0,0 +1,46 @@ +# The is_bad_version API is already defined for you. +# @param {Integer} version +# @return {boolean} whether the version is bad +# def is_bad_version(version): + +# @param {Integer} n +# @return {Integer} +def first_bad_version(n) + left = 1 + right = n + + while left < right do + mid = (left + right).div(2) + + if is_bad_version(mid) then + right = mid + else + left = mid + 1 + end + end + + return left +end + +RSpec.describe "first_bad_version" do + it "n = 5, bad = 4" do + def is_bad_version(n) + return n >= 4 + end + expect(first_bad_version(5)).to eq(4) + end + + it "n = 1, bad = 1" do + def is_bad_version(n) + return n >= 1 + end + expect(first_bad_version(1)).to eq(1) + end + + it "n = 1000000, bad = 76192" do + def is_bad_version(n) + return n >= 76192 + end + expect(first_bad_version(1000000)).to eq(76192) + end +end diff --git a/study-plan/algorithm/day-1/search-insert-position.rb b/study-plan/algorithm/day-1/search-insert-position.rb new file mode 100644 index 0000000..b2c2bf7 --- /dev/null +++ b/study-plan/algorithm/day-1/search-insert-position.rb @@ -0,0 +1,35 @@ +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer} +def search_insert(nums, target) + left = 0 + right = nums.size + + while left < right do + mid = (left + right).div(2) + + if nums[mid] == target then + return mid + elsif nums[mid] < target then + left = mid + 1 + else + right = mid + end + end + + return left +end + +RSpec.describe "search_insert" do + it "nums = [1,3,5,6], target = 5" do + expect(search_insert([1,3,5,6], 5)).to eq(2) + end + + it "nums = [1,3,5,6], target = 2" do + expect(search_insert([1,3,5,6], 2)).to eq(1) + end + + it "nums = [1,3,5,6], target = 7" do + expect(search_insert([1,3,5,6], 7)).to eq(4) + end +end