[LeetCode]Find Minimum in Rotated Sorted Array
Find Minimum in Rotated Sorted Array
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.
O(n)时间复杂度的算法很容易实现,二分搜索可以将时间复杂度降为O(logn)。
要搞清楚各个参数测设置以及判定条件的设置。
1 class Solution { 2 public: 3 int findMin(vector<int>& nums) { 4 if(nums.size()==0) return 0; 5 int left=0,right=nums.size()-1; 6 while(left<right && nums[left]>=nums[right]) 7 { 8 int mid = (left+right)/2; 9 if(nums[mid]>nums[right]) 10 { 11 left = mid+1; 12 } 13 else 14 { 15 right = mid; 16 } 17 } 18 return nums[left]; 19 } 20 };