Find Minimum in Rotated Sorted Array II

题目:

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.

The array may contain duplicates.

分析:

这道题目第二遍做的时候算法比第一遍聪明一点。

解法:

class Solution {
public:
    /**
     * @param num: the 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[start] == num[end] || num[mid] == num[end]) {
                end--;
                continue;
            }
            if (num[mid] > num[end]) {
                start = mid;
            } else {
                end = mid;
            }
        }
        return (num[start] < num[end]) ? num[start] : num[end];
    }
};

results matching ""

    No results matching ""