[leetcode刷题系列]Search in Rotated Sorted Array II

- - 这题反正我是没想到确定性的logn的算法。 我的解法最坏情况下是O(n)


class Solution {
public:
    bool search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n <= 0)
            return false;
        if(A[0] == target || A[n - 1] == target)
            return true;
        while(n > 1)
            if(A[n - 1] == A[n - 2])
                -- n;
            else
                break;
        if(A[n - 1] == A[0])
            --n;
        if(n <= 0)
            return false;
        int low = 0, high = n - 1, mid;
        while(low <= high)
            if(A[mid = low + high >> 1] < A[0]) high = mid - 1; else low = mid + 1;
        int p = low;
        // left
        low = 0, high = p - 1;
        while(low <= high)
            if(A[mid = low + high >> 1] >= target) high = mid - 1;else low = mid + 1;
        if(low >= 0 && low < n && A[low] == target)
            return true;
        low = p, high = n - 1;
        while(low <= high)
            if(A[mid = low + high >> 1] >= target) high = mid - 1;else low = mid + 1;
        if(low >= 0 && low < n && A[low] == target)
            return true;
        return false;
    }
};


你可能感兴趣的:([leetcode刷题系列]Search in Rotated Sorted Array II)