153. Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order 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.
Example 1:
Input:[3,4,5,1,2]
Output:1Example 2:
Input:[4,5,6,7,0,1,2]
Output:0Thoughts:
Binary Search:
1st method : To find the minimum, use the nums[mid] to compare with nums[right]:
2nd method: To compare with nums[left] and at the end compare the found result with start and end value (since this method would "assume there is a pivot")
Code1:
class Solution {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right){
int mid = left + (right - left >> 1);
if (nums[mid] > nums[right]){
left = mid + 1;
}
else
right = mid;
}
return nums[left];
}
}Code2:
Last updated
Was this helpful?