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