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.
The array may contain duplicates.
一刷
public class Solution {
public int findMin(int[] nums) {
int lo = 0, hi = nums.length-1;
while(lo<hi){
if(nums[lo]<nums[hi]) return nums[lo];
int mid = lo+(hi-lo)/2;
if(nums[mid]>nums[hi]){//left half is sorted
lo = mid+1;
}
else if(nums[mid]<nums[hi]){//right half is sorted
hi = mid;
}
else hi--;
}
return nums[lo];
}
}
二刷
由于是Rotated Sorted Array, 并且最低点在lo和hi之间,那么lo和hi之间只可能是
所以当noms[lo]<nums[hi]的时候,说明lo就是最低点。
当nums[mid]==nums[lo]的时候,并没有其它信息,只能将lo++, 因为lo和mid相等,可以缩短一个查找范围(mid仍在范围中)
public class Solution {
public int findMin(int[] nums) {
int lo = 0, hi = nums.length-1;
while(lo<hi){
int mid = lo + (hi-lo)/2;
if(nums[lo]<nums[hi]) return nums[lo];
if(nums[mid]>nums[lo]){//on the right side
lo = mid+1;
}
else if(nums[mid]<nums[lo]){
hi = mid;//on the left side;
}
else lo++;
}
return nums[lo];
}
}