题目要求如下:
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.
本题题目难度为中等,但是我觉得难度远胜难度为hard的 Search in Rotated Sorted Array本题的代码如下:
class Solution {
public:
bool search(int A[], int n, int target) {
int low = 0;
int high = n - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (A[mid] == target)
return true;
if (A[mid] > A[low]) {
/* left part are sorted */
if (A[mid] > target) {
if (A[low] > target)
low = mid + 1;
else if (A[low] == target)
return true;
else
high = mid - 1;
}
else if (A[mid] < target) {
low = mid + 1;
}
}
else if (A[mid] < A[low]) {
/* right part are sorted */
if (A[mid] > target) {
high = mid - 1;
}
else if (A[mid] < target) {
if (A[high] > target)
low = mid + 1;
else if (A[high] == target)
return true;
else
high = mid - 1;
}
}
else
++low;
}
return false;
}
};
这个思路不是我想出来的,是我看讨论区后,觉得这种算法最为简洁:
这个的精髓在与最后一个++low,如果A[mid] == A[low],证明之间的所有元素都是相等,所以要一只++low,这样处理完之后,就可以判断左边是sorted还是右边是sorted的。。比如11131,如果仅看A[low],A[high],A[mid],无法判断出哪边是sorted的,其实pivot在右边3后面那个1,所以左边的是完全sorted的,上面描述的处理可以把前面的1都消掉,当然上面那个例子是worst case, 时间复杂度也接近O(N),排除特殊条件后,逻辑如下:
1A[mid] > A[low]:low-mid之间sorted过
1.1 A[mid] > target
1.1.1.A[low] > target: target在mid-high
1.1.2A[low] == target找到
1.1.3A[low] < target: target在low-mid
1.2A[mid] < target:: target在mid-high
2.A[mid] < A[low]:mid-high之间sorted过
2.1 A[mid] > target: target在low-mid
2.2A[mid] < target:
2.2.1 A[high] > target: mid-high之间
2.2.2 A[high] == target:相等
2.2.3 A[high] < target: low-mid之间