Question
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Solution
-
暴力求解,时间复杂度O(n)
-
二分查找。虽然是旋转数组,但是总有一部分是有序的,我们可以直接判断目标是否在有序的那一部分,如果不在,那么就在另外一部分。先判断左半部分是否有序。
-
因为考虑到首、尾、中间值,可能都相同的情况,比如11101和10111,0可能在左边也也可能在右边,这个时候只能依次遍历。
-
时间复杂度O(lgn)
Code
class Solution {
public:
bool search(int A[], int n, int target) {
int i = 0;
int j = n - 1;
while (i <= j) {
int mid = (i + j) >> 1;
if (A[mid] == target)
return true;
// 必须依次查找
if (A[i] == A[mid] && A[mid] == A[j]) {
for (int k = i; k <= j; k++) {
if (A[k] == target)
return true;
}
return false;
}
if (A[i] <= A[mid]) {
// 判断是否在左边有序的部分里面,不在就在另外一部分
if (target >= A[i] && target <= A[mid])
j = mid - 1;
else
i = mid + 1;
} else if (A[mid] <= A[j]) {
// 判断是否在右边有序的部分里面,不在就在另外一部分
if (target >= A[mid] && target <= A[j])
i = mid + 1;
else
j = mid - 1;
}
}
return false;
}
};