Suppose an array sorted in ascending order 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.
Python
# Time O(n)
# Space O(1)
# Method : direct search
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min = nums[0]
for i in range(len(nums)):
if nums[i] < min:
min = nums[i]
return min
# Time O(log(n))
# Space O(1)
# Method : Binary search
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] < nums[right]:
right = mid
else:
left = mid + 1
# 最后一次 left==right外里,此時袖订,mid即為所求梗劫,當仍進入循環(huán)屋剑;
# 此時谍肤,a[mid]==a[right]然痊,導致left多加了1
return nums[left - 1]
C++
class Solution {
public:
int findMin(vector<int>& nums) {
int min = nums[0];
int L = nums.size();
for(int i=0;i<L;i++){
if(nums[i] < min){
min = nums[i];
}
}
return min;
}
};