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.
测试例子:[1,2] [2,1] [4,5,6,7,8,9,10,11,1,2,3]
//vs2012测试代码 //方法一:二分查找 //主要思想是二分查找,对于num[left .. right]数组,命mid=(left+right)/2,那么存在一下三种情况: //1)num[left]<num[right]: 这时,整个数组是有序的,因此直接返回num[left]即可; //2)num[left]>=num[right] && num[left]>num[mid]:这时,num[mid..right]有序,那么最小值一定出现在num[left..mid]之中,抛弃num[mid+1..right],则取right=mid; //3)num[left]>=num[right] && num[left]<=num[mid] : 这时,num[left..mid]是有序的,所以最小值一点个出现在num[mid+1..right]中,抛弃num[left..mid],则取left=mid+1; #include<iostream> #include<vector> #include<algorithm> using namespace std; #define N 4 class Solution { public: int findMin(vector<int> &num) { int size = num.size(); int left = 0 , right = size-1; while( left<right) { //all sorted if( num[left] < num[right]) break; else { int mid = left + (right-left)/2; //Sorted from mid to right //The smallest must in num[left..mid] if( num[mid] < num[left]) right = mid; //Sorted from beg to mid //The smallest must in num[mid+1..end] else left = mid+1; } } return num[left]; } }; int main() { vector<int> num; int a; for(int i=0; i<N; i++) { cin>>a; num.push_back(a); } Solution lin; cout<<lin.findMin(num)<<endl; return 0; }
//方法一:自测Accepted //主要思想是二分查找,对于num[left .. right]数组,命mid=(left+right)/2,那么存在一下三种情况: //1)num[left]<num[right]: 这时,整个数组是有序的,因此直接返回num[left]即可; //2)num[left]>=num[right] && num[left]>num[mid]:这时,num[mid..right]有序,那么最小值一定出现在num[left..mid]之中,抛弃num[mid+1..right],则取right=mid; //3)num[left]>=num[right] && num[left]<=num[mid] : 这时,num[left..mid]是有序的,所以最小值一点个出现在num[mid+1..right]中,抛弃num[left..mid],则取left=mid+1; class Solution { public: int findMin(vector<int> &num) { int size = num.size(); int left = 0 , right = size-1; while( left<right) { //all sorted if( num[left] < num[right]) break; else { int mid = left + (right-left)/2; //Sorted from mid to right //The smallest must in num[left..mid] if( num[mid] < num[left]) right = mid; //Sorted from beg to mid //The smallest must in num[mid+1..end] else left = mid+1; } } return num[left]; } };
//方法二:其他版本 class Solution { public: int findMin(vector<int> &num) { int length = num.size()-1; int left=0 , right=length; while( left<=right) { int mid = left + (right-left)/2; if( num[mid] > num[length]) { left = mid + 1; } else { right = mid - 1; } } return num[left]; } };
//方法三:书中版本 class Solution { public: int findMin(vector<int> &num) { int left = 0; int right = num.size()-1; int mid = left; while(num[left]>num[right]) { if(right-left == 1) { mid = right; break; } mid = (right+left)/2; if(num[left] > num[mid]) right = mid; else left = mid; } return num[mid]; } };