您的位置:首页 > 其它

LeetCode Search in Rotated Sorted Array II

2015-02-02 19:43 155 查看
Search in Rotated Sorted Array II

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.
class Solution {
public:
bool search(int A[], int n, int target) {
int i = 0, j = n - 1, m = (i + j) / 2;
bool flag = false;
while(i <= j) {
if(i != j && A[i] == A[j]) {
flag = true;
break;
}
if(A[i] <= A[j]) {
if(target == A[m]) return true;
else if(target > A[m]) i = m + 1;
else j = m - 1;
}
else {
if(A[m] > A[j]) {
if(target == A[m]) return true;
if(target >= A[i] && target < A[m]) j = m - 1;
else i = m + 1;
}
else {
if(target == A[m]) return true;
if(target > A[m] && target <= A[j]) i = m + 1;
else j = m - 1;
}
}
m = (i + j) / 2;
}
if(flag) {
for(int k = i; k <= j; k++) {
if(A[k] == target) return true;
}
}
return false;
}
};


思路:算法最坏情况时间复杂度O(n),平均O(logn)。
还是Search
in Rotated Sorted Array的算法,算法走到A[i] == A[j] && i != j的情况时,无法再判断左右,此时只能全部扫描一遍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: