Created
April 2, 2015 23:07
-
-
Save walkingtospace/f58ac0f00668646586d4 to your computer and use it in GitHub Desktop.
find-minimum-in-rotated-sorted-array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ | |
//Linear search: O(n) | |
class Solution { | |
public: | |
int findMin(vector<int> &num) { | |
int min = INT_MAX; | |
for(int i=0; i< num.size() ; ++i) { | |
if(min > num[i]) min = num[i]; | |
} | |
return min; | |
} | |
};*/ | |
/* | |
//modified binary search: O(log n) | |
pick the middle element of the given subarray | |
comparison 1)left-end 2) right-end | |
if( right-end < mid || left-end > mid), then the 'start' element should be that side. | |
*/ | |
class Solution { | |
public: | |
int findMin(vector<int> &num) { | |
int left = 0; | |
int right = num.size()-1; | |
int min = 0; | |
if(num.size() == 1) { //exception | |
return num[0]; | |
} | |
while(left < right) { | |
int mid = (left+right)/2; | |
if(num[mid] > num[right]) { | |
left = mid; | |
} else if(num[mid] < num[left]) { | |
right = mid; | |
} else { | |
return num[0]; | |
} | |
if(abs(left-right) <= 1) { | |
if(num[left] < num[right]) { | |
return num[left]; | |
} else { | |
return num[right]; | |
} | |
} | |
} | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment