1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

algorithm(i): add day 1

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-01-19 12:52:54 +01:00
parent afd4b06f50
commit bf4f7c2ff5
No known key found for this signature in database
GPG key ID: 332171FADF1DB90B
3 changed files with 112 additions and 0 deletions

View file

@ -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

View file

@ -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

View file

@ -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