153. Find Minimum in Rotated Sorted Array
Problem Statement¶
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2]if it was rotated4times.[0,1,2,4,5,6,7]if it was rotated7times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
Solution¶
Initial Approach¶
// if left is smaller and right is smaller -> right is the answer
// if left is smaller and right is greater -> call on right
// if left is smaller and current is the last element -> first element is the answer
Approach 2¶
- low,high pointers
- if midValue > highValue -> update lowIndex to midIndex+1
- if
midValue <= highValue-> updatehighValue to mindIndex; - continue till
low < high - return value for
nums\[low]
class Solution {
public:
int findMin(vector<int>& nums) {
int low = 0;
int high = nums.size()-1;
int highValue;
int midIndex, midValue;
while(low < high){
midIndex = (low + high)/2;
midValue = nums[midIndex];
highValue = nums[high];
if(midValue > highValue)
low = midIndex+1;
else
high = midIndex;
}
return nums[low];
}
};
class Solution {
public:
int findMin(vector<int>& nums) {
int low = 0;
int high = nums.size()-1;
int ans = INT_MAX;
while(low <= high){
int mid = low + (high-low)/2;
if(nums[mid] < ans)
ans = nums[mid];
if(nums[low] <= nums[mid]){ // left side of the array is sorted
// since left is sorted, we update min
ans = min(ans,nums[low]);
low = mid+1;
// now we have smallest value from sorted array in ans (left->mid)
}else{ // answer not in left since left > mid
ans = min(ans, nums[mid]);
high = mid-1;
}
}
return ans;
}
};