leetcode
leetcode copied to clipboard
Better solution for Find Minimum In Rotated Sorted Array - Java
Actually, in this problem we can simplify the logic:
- if
midvalue <hivalue -> search to the left inclusive mid. Because we don't need to look at any number to the right, but currentmidvalue should be kept as it can be an answer. - else case. More precisely, if rightmost value is not bigger - it means it will be smaller as only unique values are presented. And it means that to the left there will be the values preceding to the mid => go right as we have deflection point to the right
Code
class Solution {
public int findMin(int[] nums) {
// at least 1 element in nums. Elements are unique. [5,0,1,2,4]; [2,1]
int lo = 0;
int hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < nums[hi]) {
/*
go left and keep curr mid as it may be our answer
we are guaranteed that min will be there as left
is smaller -> deflection somewhere to the left
*/
hi = mid;
} else {
// go right
lo = mid + 1;
}
}
return nums[lo];
}
}