假設一個旋轉排序的數組其起始位置是未知的(比如0 1 2 4 5 6 7 可能變成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
你可以假設數組中不存在重複的元素。
注意事項
You may assume no duplicate exists in the array.
給出[4,5,6,7,0,1,2] 返回 0
/**
* 定義兩個指針,start,end,取中間值,
* 分別與倆指針比較,決定在那邊查找
*///博客
public class Solution {
public int findMin(int[] nums) {
// write your code here
int start = 0;int end = nums.length-1;
while(start<end){
if(nums[start] < nums[end]) {//沒有旋轉
return nums[start];
}
int mid = start + (end-start)/2;
if(nums[start]<=nums[mid]){//只有等於才能退出,和return
start = mid+1;
}else {//nums[start]>nums[mid]
end= mid;
}
}
return nums[start];
}
}