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

简单想下, 其实比较简单, 三次二分。

一次二分用来找数组的分界点

然后分别两次二分在分界的左右查找target就可以了

log(n)的算法复杂度

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


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