-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path35.1_search_insert_position.rb
67 lines (52 loc) · 1.34 KB
/
35.1_search_insert_position.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true
# https://leetcode.com/problems/search-insert-position/
require_relative '../test_helper'
# Runtime: 99 ms, faster than 60.52% of Ruby online submissions for Search Insert Position.
# Memory Usage: 211.1 MB, less than 60.30% of Ruby online submissions for Search Insert Position.
class Solution
class << self
def search_insert(nums, target)
left = 0
right = nums.size - 1
return left if target <= nums[left]
return right + 1 if target > nums[right]
while left <= right
pivot = (left + right) / 2
if nums[pivot] < target
left = pivot + 1
elsif nums[pivot] > target
right = pivot - 1
else
return pivot
end
end
left
end
end
end
class TestSolution < Minitest::Test
def test_1
nums = [1, 3, 5, 6]
target = 5
output = 2
assert_equal output, Solution.search_insert(nums, target)
end
def test_2
nums = [1, 3, 5, 6]
target = 2
output = 1
assert_equal output, Solution.search_insert(nums, target)
end
def test_3
nums = [1, 3, 5, 6]
target = 7
output = 4
assert_equal output, Solution.search_insert(nums, target)
end
def test_4
nums = [1, 3]
target = 2
output = 1
assert_equal output, Solution.search_insert(nums, target)
end
end