Find Minimum in Rotated Sorted Array

LeetCode #153


Description:

Suppose an array sorted in ascending order 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.

Example:

Note

Idea:

这个与Search in Rotated Sorted Array非常像,但是需要用[start, end] but not [start, end).但update的方式几乎一样。

Time: O(logn).

Code:

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 - start) / 2;
            if(nums[start]<=nums[mid]) start = mid +1;
            else end = mid;
        }
        return nums[start];
    }
};

results matching ""

    No results matching ""