lintcode--尋找旋轉排序數組中的最小值

假設一個旋轉排序的數組其起始位置是未知的(比如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];
    }
}



發佈了124 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章