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.
Difficulty: 88. Refer to the online analysis. The only difference between the analysis and search in rotated sorted array II is that the elements in this question are duplicated. However, it is precisely because of this condition that complicated cases occur and even affect the time complexity of the algorithm. It turns out that we rely on the Size relationship between the intermediate and edge elements to determine which half is not affected by rotate and is still ordered. Now, because of the repeated appearance, If we encounter the same situation between the center and the edge, we will lose the ordered information, because each side may be ordered. If the original array is {, 3, 3, 3, 3}, it may be {3, 3, 3, 3, 3, 1, 2}, or {3, 1, 2, 3, 3, 3, 3} after rotation, 3}. In this way, we determine that the left and center are both 3. If we are looking for 1 or 2, we do not know which half to jump. The solution can only be to move the edge step until the edge and the middle are not equal or encounter, which leads to the possibility that the edge cannot be halved. Therefore, the worst case (for example, if all elements are one element, or only one element is different from other elements, and he is in the last one) will show every moving step, n steps in total, the time complexity of the algorithm changes to O (n ).
The reason why the edge can be moved is that when the edge and the center are equal, the center clearly knows that it is not equal to the target (otherwise it has already been returned), then the edge element is not equal to the target, therefore, this element will not affect the result.
1 public class Solution { 2 public boolean search(int[] A, int target) { 3 if (A == null || A.length == 0) { 4 return false; 5 } 6 int l = 0; 7 int r = A.length - 1; 8 while (l <= r) { 9 int mid = (l + r) / 2;10 if (A[mid] == target) return true;11 else if (A[mid] > A[r]) {12 if (target>=A[l] && target<A[mid]) {13 r = mid - 1;14 }15 else {16 l = mid + 1;17 }18 }19 else if (A[mid] < A[r]) {20 if (target>A[mid] && target<=A[r]) {21 l = mid + 1;22 }23 else {24 r = mid - 1;25 }26 }27 else {28 r--; // A[mid] == A[r], and we know A[mid] != target, so A[r] can be taken away, it does not influence the result29 }30 }31 return false;32 }33 }
Leetcode: Search in rotated sorted array II