Leetcode 153. Find Minimum in Rotated Sorted Array

  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.
class Solution {
public:
int findMin(vector<int>& nums) {
int start = 0;
int end = nums.size() - 1;

while ( end >= start) {
if (start + 1 == end) {
return nums[start] < nums[end] ? nums[start] : nums[end];
}

int mid = (start + end) / 2;
if (nums[start] <= nums[mid] && nums[mid] <= nums[end]) {
// all are ordered
return nums[start];
} else if (nums[start] <= nums[mid]) {
// left is ordered
start = mid;
} else {
// right is ordered
end = mid;
}
}
return 0;
}
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store