leetcode problem 33 -- Search in Rotated Sorted Array

时间:2023-03-09 08:51:20
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 <= )
return -;
if (n == )
return *A == target ? : -; int begin = , end = n, mid = (begin + end) / ; if (A[begin] <= A[mid-]) {
if (target >= A[begin] && target <= A[mid-]) {
auto it = lower_bound(A, A + mid, target);
if (*it == target)
return it - A;
else
return -;
}
int res = search(A + mid, end - mid, target);
return res == - ? - : mid + res;
}
else {
if (target >= A[mid] && target <= A[end-]) {
auto it = lower_bound(A+mid, A+end, target);
if (*it == target)
return it - A;
else
return -;
}
int res = search(A + begin, mid - begin, target);
return res == - ? - : begin + res;
}
}
};