Skip to content

Commit

Permalink
Several possible approaches
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeQCarr committed Jan 21, 2023
1 parent 29df8e9 commit 6be9c09
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions ruby/0153-find-minimum-in-rotated-sorted-array.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# @param {Integer[]} nums
# @return {Integer}a

#shortest solution O(n)?
def find_min(nums)
nums.min
end

#non binary-search iterative approach O(n)
def find_min(nums)
last_num = nums.last
nums.each.with_index do |num, i|
return num if num <= last_num
end
end

#using ruby's built-in binary search O(log n)
def find_min(nums)
nums.bsearch {|num| num <= nums.last }
end

#custom binary-search O(log n)
def find_min(nums)
result = nums[0]
left = 0
right = nums.length - 1

while left <= right do
if nums[left] < nums[right]
return [result, nums[left]].min
end

mid = (left + right) / 2
result = [result, nums[mid]].min

if nums[mid] >= nums[left]
left = mid + 1
else
right = mid - 1
end
end

return result
end

0 comments on commit 6be9c09

Please sign in to comment.