mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
35 lines
752 B
Ruby
35 lines
752 B
Ruby
# @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
|