Skip to content

Instantly share code, notes, and snippets.

@stexuq
Created October 12, 2021 05:43
Show Gist options
  • Save stexuq/c210483d420996a3e7a2b25f70c373c1 to your computer and use it in GitHub Desktop.
Save stexuq/c210483d420996a3e7a2b25f70c373c1 to your computer and use it in GitHub Desktop.
class Solution {
public:
/**
* @param nums: a rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &nums) {
int n = nums.size();
int start = 0, end = n - 1;
if (nums[start] < nums[end]) return nums[start];
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[start] < nums[mid]) {
// start ~ end increase
start = mid;
} else if (nums[mid] < nums[end]) {
// start ~ mid not sure
// mid ~ end increase
end = mid;
} else {
// start > mid, mid > end, not possible
}
}
// mid is start or mid is end
if (nums[start] < nums[end]) {
return nums[start];
} else {
return nums[end];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment