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.

分析:

Finde minimum比search target简单的多,因为分类的时候就2种情况。A[mid]在上面和A[mid]在下面。

解法:

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
        if (num.size() == 0) {
            return 0;
        }
        int start = 0;
        int end = num.size() - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (num[mid] > num[end]) {
                start = mid;
            } else {
                end = mid;
            }
        }
        return (num[start] < num[end]) ? num[start] : num[end];
    }
};

results matching ""

    No results matching ""