LeetCode Search in Rotated Sorted Array II

class Solution {

public:

    bool search(int A[], int n, int target) {

        if (n < 1) return false;

        int pre = A[0];

        int wpos = 1, rpos = 1;

        while (rpos < n) {

            if (A[rpos] == pre) {

                rpos++;

            } else {

                pre = A[wpos++] = A[rpos++];

            }

        }

        n = wpos;

        

        int sep = A[n-1];

        int left = -1, right = n;

        while (left + 1 < right) {

            int mid = (left + right) / 2;

            if (sep > A[mid]) {

                right = mid;

                sep = A[mid];

            } else if (sep < A[mid]) {

                left = mid;

            } else {

                right = mid;

                break;

            }

        }

        return binary_search(A, right, target) || binary_search(A + right, n - right, target);

    }

    

    bool binary_search(int *a, int n, int target) {

        int left = -1, right = n;

        while (left + 1 < right) {

            int mid = (left + right) / 2;

            if (a[mid] > target) {

                right = mid;

            } else if (a[mid] < target) {

                left = mid;

            } else {

                return true;

            }

        }

        return false;

    }

};

多了一步去重的步骤,复杂度没什么变化,只是这样做修改了输入数据

你可能感兴趣的:(LeetCode)