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];
}