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.

http://www.lintcode.com/en/problem/find-minimum-in-rotated-sorted-array/

Discussion


一看这种就是用binary search的思想了,start, mid, end关系有四种情况:
start < mid < end ---> end = mid;
start < mid > end ---> start = mid;
start > mid > end ---> start = mid;
start > mid < end ---> end = mid;
因为是在循环(start+1<end)里嘛,不存在相等的情况的,不然start end就相邻了。再归纳一下上面四种情况发现只要比较mid和end就可以了。

Solution


class Solution {
public:
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    int findMin(vector<int> &num) {
        // write your code here
        int start = 0, end = num.size()-1;
        while(start + 1 < end) {
            int mid = start + (end-start)/2;

            if(num[mid] < num[end]) end = mid;
            if(num[mid] > num[end]) start = mid;
        }
        if(num[start] < num[end]) return num[start];
        return num[end];
    }
};

results matching ""

    No results matching ""