Find Minimum in Rotated Sorted Array
Suppose a sorted array 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.
该题仍然局部有序,仍然使用二分查找,只是判断移动游标的方式不一样,另外针对{6,5,4,3,2,1}这种case ,需要特殊处理
public static int findMin(int[] num) {
int start = 0 , end = num.length - 1;
int result = 0;
int key = (num[start] - num[end]);
while(true){
int mid = (start+end)/2;
if((num[start] - num[mid]) * key > 0){
//mid处于后半段
end = mid;
}else if((num[start] - num[mid]) * key < 0){
//mid处于前半段
start = mid;
}else {
//start ,end 都已经移动到最小值的位置
if(key < 0){
result = num[start];
}else{
result = num[end];
}
break;
}
}
//对于 有序递减 的Case,该算法将游标移动到了最大值处,此时末尾即是最小值。
return (result < num[num.length - 1]) ? result:num[num.length - 1];
}