leetcode problem 33 -- Search 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).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

思路:

  给你一个已排序好但移位了的数组,找到特定的数。画一幅图就很容易理解了。一个被旋转的有序数组A[1..n],假定转折点是A[k],那么A[k+1] < A[k+2] < ... < A[n] < A[1] < A[2] < ... < A[k]

  可以用二分查找稍微改点型:虽然我们不知道转折点k在哪,但是我们还是可以通过比较A[mid]与A[start],A[end]来确定要找的目标书target是在A[start,...,mid]中,还是在A[mid+1,...,end]  所以时间复杂度还是lg(n)

代码:

Runtime: 12 ms

class Solution{
public:
    int search(int A[], int n, int target) {
        if (n <= 0)
            return -1;
        if (n == 1)
            return *A == target ? 0 : -1;

        int begin = 0, end = n, mid = (begin + end) / 2;

        if (A[begin] <= A[mid-1]) {
            if (target >= A[begin] && target <= A[mid-1]) {
                auto it = lower_bound(A, A + mid, target);
                if (*it == target)
                    return it - A;
                else 
                    return -1;
            }
            int res = search(A + mid, end - mid, target);
            return res == -1 ? -1 : mid + res;
        }
        else {
            if (target >= A[mid] && target <= A[end-1]) {
                auto it = lower_bound(A+mid, A+end, target);
                if (*it == target)
                    return it - A;
                else
                    return -1;
            }    
            int res = search(A + begin, mid - begin, target);
            return res == -1 ? -1 : begin + res;
        }
    }
};
原文地址:https://www.cnblogs.com/lysuns/p/4453472.html