Follow up for "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 1:
跟第一题类似 Search in Rotated Sorted Array
以下为回顾第一题的解析 :
和一般的二分法搜索没有太多区别。
问题是我们每次要找出正常排序的部分,你只需要比较mid, left,如果它们是正序,就代表左边是
正常排序,而右边存在断开的情况,也就是因为Rotated发生不正常序列。
例如:
4567012 如果我们取mid为7,则左边是正常序列,而右边7012不正常。
然后 我们再将target与正常排序的这边进行比较,如果target在左边,就丢弃右边,反之,丢弃
左边。一次我们可以扔掉一半。和二分搜索一样快。
=======================
第二题与第一题的区别是:
如果发现A[Mid] == A[Left] 我们不认为左边是有序的。因为有可能是这样的序列:
如 2222 34 22 | 2222 2222
如以上序列中,我们不能判断为左边有序,因为左边是存在切割点的,所以,当遇到这种情况时,
直接把Left 指针 加1,而不是丢弃一半。
而这里存在一个小的数学问题:
1. 当我们发现左边是降序时,右边一定是有序的(断口一定在左边嘛)
2. 当发现左边是升序,那么肯定不会有断口,左边一定是连续有序的。
3. 当相等,无法判断,则丢弃一个元素即可。(其实改进的算法是,可以这时再判断右边是不是降序。)
对复杂度的影响:
最差复杂度为O(n),因为极端情况是所有的值相等。而有多复杂取决于有多少重复数字。假设重复
数字为m,总数为n. 则复杂度大概会是O(m + Log(n)). 因为如果我们找到一些有序序列仍然是可以扔掉一
半的。
查看代码时,请注意细微的 <= 和 < 的差别。
版本1:
1 public boolean search1(int[] A, int target) { 2 if (A == null || A.length == 0) { 3 return false; 4 } 5 6 int l = 0; 7 int r = A.length - 1; 8 9 while (l < r - 1) { 10 int mid = l + (r - l) / 2; 11 12 if (A[mid] == target) { 13 return true; 14 } 15 16 // left sort 17 if (A[mid] > A[l]) { 18 // out of range. 19 if (target > A[mid] || target < A[l]) { 20 l = mid + 1; 21 } else { 22 r = mid - 1; 23 } 24 // right sort. 25 } else if (A[mid] < A[l]) { 26 // out of range. 27 if (target < A[mid] || target > A[r]) { 28 r = mid - 1; 29 } else { 30 l = mid + 1; 31 } 32 } else { 33 // move one node. 34 l++; 35 } 36 } 37 38 if (A[l] == target || A[r] == target) { 39 return true; 40 } 41 42 return false; 43 }