Search in Rotated Sorted Array II
Q:
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.
当数组中无重复数字的时候,使用二分法,通过比较最左边,中间以及target的大小关系可以确认是向左走或向右走。
当数组中有重复数字的时候,如果最左边,中间以及最右边的数字均相等的时候,既可能向左找也可能向右找,这种情况需要特殊处理一下,这里就是先查看左边的数字是不是全部相等,如果是就向右边找,如果不是就找左边。还有更好的办法么。得想一想。
class Solution { public: bool search(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function if (n < 0) return false; int begin = 0; int end = n - 1; while (begin <= end) { int pos = (begin + end) / 2; if (A[pos] == target) { return true; } if (A[begin] == target) return true; if (A[pos] < target) { if (A[begin] > target) { begin = pos + 1; } else { if (A[begin] < A[pos]) { begin = pos + 1; } else if (A[begin] == A[pos]) { if (A[end] == A[pos]) { int i = begin; for (; i < pos; ++i) { if (A[i] != A[begin]) { begin = i; end = pos - 1; break; } } if (i == pos) { begin = pos + 1; } } else { begin = pos + 1; } } else { end = pos - 1; } } } else { if (A[begin] < target) { end = pos - 1; } else { if (A[begin] < A[pos]) { begin = pos + 1; } else if (A[begin] == A[pos]) { if (A[end] == A[pos]) { int i = begin; for (; i < pos; ++i) { if (A[i] != A[begin]) { begin = i; end = pos - 1; break; } } if (i == pos) { begin = pos + 1; } } else { begin = pos + 1; } } else { end = pos - 1; } } } } return false; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号