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.
https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
思路:类似Search in Rotated Sorted Array的思路,只不过现在的问题是有重复,可能出现a[l]==a[m]的极端情况,无法判断哪半边有序,因此这种情况下只能一步一步移动l 直到不相等然后通过二分判断。
复杂度:极端情况每次都是减一 而不是减去一半,所以复杂度是O(N)。

/** * http://blog.csdn.net/linhuanmars/article/details/20525681 * * @author jd * */ public class Solution { public boolean search(int[] A, int target) { if (A == null || A.length == 0) return false; int l = 0; int r = A.length - 1; while (l <= r) { int m = (l + r) / 2; if (A[m] == target) return true; if (A[m] > A[l]) { if (A[m] > target && A[l] <= target) { r = m - 1; } else { l = m + 1; } } else if (A[m] < A[l]) { if (A[m] < target && A[r] >= target) { l = m + 1; } else { r = m - 1; } } else { l++; } } return false; } public static void main(String[] args) { System.out.println(new Solution().search(new int[] { 3, 1, 1 }, 3)); System.out.println(new Solution().search(new int[] { 2, 3, 3, 3, 3 }, 2)); System.out.println(new Solution().search(new int[] { 3, 2, 3, 3, 3 }, 2)); System.out.println(new Solution().search(new int[] { 3, 3, 3, 2, 3 }, 2)); System.out.println(new Solution().search(new int[] { 3, 3, 3, 3, 2 }, 2)); } }
第二遍记录:
相比没有重复元素的,当A[left]==A[mid]的时候,只能一步一步移动left直到不相等。
public class Solution { public boolean search(int[] A, int target) { if(A==null||A.length==0) return false; int left=0,right=A.length-1,mid=0; while(left<=right){ mid = left+(right-left)/2; if(target==A[mid]) return true; if(A[left]<A[mid]){ if(target>=A[left]&&target<A[mid]){ right=mid-1; }else{ left=mid+1; } }else if(A[left]>A[mid]){ if(target>A[mid]&&target<=A[right]){ left=mid+1; }else{ right=mid-1; } }else{ left++; } } return false; } }
参考: