Problem Statement
(Source) Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Find the minimum element.
You may assume no duplicate exists in the array.
Analysis
Be naive first. One-pass scan can find the minimum element.
class Solution(object):
def findMin(self, nums):
return min(nums)
The time complexity is O(n)
.
Considering that the array is rotated at most once. If the array isn’t rotated at all, then the first element would be the minimum. Otherwise, we can do a linear scan, and the first element that is smaller that its previous element is the minimum.
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in xrange(1, len(nums)):
if nums[i] < nums[i - 1]:
return nums[i]
return nums[0]
The time complexity is O(n)
at the worst case.
The optimised solution would be using Binary Search
.
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) >> 1
if nums[mid] > nums[lo]:
if nums[lo] <= nums[hi]:
return nums[lo]
else:
lo = mid + 1
elif nums[mid] < nums[lo]:
hi = mid
else:
return min(nums[lo], nums[hi])
The time complexity is O(logn) .