leetcode--Find Minimum in Rotated Sorted Array --C++

問題:

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.

思路:典型的二分查找,而且這個題簡單了,裏面假設沒有重複元素。若有重複元素,則要複雜一點,具體的請看:劍指offer---旋轉數組的最小數字.還有就是下一個題:

Find Minimum in Rotated Sorted Array II

 

class Solution {
public:
    int findMin(vector<int>& nums) {
        int start = 0;
        int end = nums.size() - 1;
        while(start < end)
        {
            if(nums[start] < nums[end])
                return nums[start];
            int mid = (start + end) / 2;
            if(nums[start] <= nums[mid])   //這裏的這個=號很關鍵,因爲mid可能和start相同。
                start = mid + 1;
            else
                end = mid;
        }
        return nums[start];
        
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章