题目地址:
https://leetcode.com/problems/search-in-rotated-sorted-array/
在旋转数组 A A A里找数。
用二分法。先找到分界点,然后根据target在左半边还是右半边再搜索一次即可。分界点满足的性质是,它是小于 A [ 0 ] A[0] A[0]的第一个数。代码如下:
class Solution {
public:
int search(vector<int>& a, int x) {
int n = a.size(), l = 0, r = n - 1;
if (l > r) return -1;
while (l < r) {
int mid = l + (r - l >> 1);
if (a[mid] < a[0]) r = mid;
else l = mid + 1;
}
if (a[l] < a[0]) {
if (a[0] <= x && x <= a[l - 1]) r = l - 1, l = 0;
else r = n - 1;
} else {
l = 0, r = n - 1;
}
while (l < r) {
int mid = l + (r - l >> 1);
if (a[mid] >= x) r = mid;
else l = mid + 1;
}
return a[l] == x ? l : -1;
}
};
时间复杂度 O ( log n ) O(\log n) O(logn),空间 O ( 1 ) O(1) O(1)。
也可以一遍二分。取中点然后看两边是否有序,这样就可以判断出target在哪个半边了。代码如下:
class Solution {
public:
int search(vector<int>& a, int x) {
int n = a.size(), l = 0, r = n - 1;
if (l > r) return -1;
while (l < r) {
int mid = l + (r - l >> 1);
if (a[mid] == x) return mid;
if (a[0] <= a[mid]) {
if (a[0] <= x && x <= a[mid])
r = mid;
else
l = mid + 1;
} else {
if (a[mid + 1] <= x && x <= a[n - 1])
l = mid + 1;
else
r = mid - 1;
}
}
return a[l] == x ? l : -1;
}
};
时空复杂度相同。