Skip to content

Commit 6be9c09

Browse files
committed
Several possible approaches
1 parent 29df8e9 commit 6be9c09

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: ruby/0153-find-minimum-in-rotated-sorted-array.rb

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# @param {Integer[]} nums
2+
# @return {Integer}a
3+
4+
#shortest solution O(n)?
5+
def find_min(nums)
6+
nums.min
7+
end
8+
9+
#non binary-search iterative approach O(n)
10+
def find_min(nums)
11+
last_num = nums.last
12+
nums.each.with_index do |num, i|
13+
return num if num <= last_num
14+
end
15+
end
16+
17+
#using ruby's built-in binary search O(log n)
18+
def find_min(nums)
19+
nums.bsearch {|num| num <= nums.last }
20+
end
21+
22+
#custom binary-search O(log n)
23+
def find_min(nums)
24+
result = nums[0]
25+
left = 0
26+
right = nums.length - 1
27+
28+
while left <= right do
29+
if nums[left] < nums[right]
30+
return [result, nums[left]].min
31+
end
32+
33+
mid = (left + right) / 2
34+
result = [result, nums[mid]].min
35+
36+
if nums[mid] >= nums[left]
37+
left = mid + 1
38+
else
39+
right = mid - 1
40+
end
41+
end
42+
43+
return result
44+
end

0 commit comments

Comments
 (0)