题目:
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.
解题思路:
This problem is similar to “Search in Rotated Sorted Array”. But there could be duplicates.
In problem “Search in Rotated Sorted Array”, we compare A[left] with A[mid] to determine which part does not contains the rotate pivot. But in this problem, A[left] could be equal to A[mid]. To solve this problem, we can let just add 1 to left when we face A[left] == A[mid] and continue the algorithm.
1 public class Solution { 2 public boolean search(int[] A, int target) { 3 int start = 0; 4 int end = A.length - 1; 5 while (start <= end) { 6 int mid = (start + end) / 2; 7 if (A[mid] == target) 8 return true; 9 if (A[start] < A[mid]) { 10 if (target >= A[start] && target < A[mid]) 11 end = mid - 1; 12 else 13 start = mid + 1; 14 } else if (A[start] > A[mid]) { 15 if (target > A[mid] && target <= A[end]) //注意边界条件 16 start = mid + 1; 17 else 18 end = mid - 1; 19 } else 20 start++; 21 } 22 return false; 23 } 24 }
Complexity
The worst case complexity will become O(n).
和Search in Rotated Sorted Array唯一的区别是这道题目中元素会有重复的情况出现。不过正是因为这个条件的出现,出现了比较复杂的case,甚至影响到了算法的时间复杂度。原来我们是依靠中间和边缘元素的大小关系,来判断哪一半是不受rotate影响,仍然有序的。而现在因为重复的出现,如果我们遇到中间和边缘相等的情况,我们就丢失了哪边有序的信息,因为哪边都有可能是有序的结果。假设原数组是{1,2,3,3,3,3,3},那么旋转之后有可能是{3,3,3,3,3,1,2},或者{3,1,2,3,3,3,3},这样的我们判断左边缘和中心的时候都是3,如果我们要寻找1或者2,我们并不知道应该跳向哪一半。解决的办法只能是对边缘移动一步,直到边缘和中间不在相等或者相遇,这就导致了会有不能切去一半的可能。所以最坏情况(比如全部都是一个元素,或者只有一个元素不同于其他元素,而他就在最后一个)就会出现每次移动一步,总共是n步,算法的时间复杂度变成O(n)。
九章算法的模板解法:
1 public class Solution { 2 public boolean search(int[] nums, int target) 3 { 4 if (nums==null||nums.length==0) 5 return false; 6 7 int start=0; 8 int end=nums.length-1; 9 10 while(start+1<end) 11 { 12 int mid = (start+end)/2; 13 if(nums[start]>nums[mid]) //左边无序,右边有序 14 { 15 if(target>nums[mid]&&target<=nums[end])start=mid; 16 else end=mid; 17 18 19 } 20 else if (nums[start]<nums[mid]) //左边有序,右边无序 21 { 22 if(target>=nums[start]&&target<nums[mid])end=mid; 23 else start=mid; 24 } 25 else //nums[start]==nums[mid] 26 { 27 start++; 28 } 29 30 } 31 32 if(nums[start]==target)return true; 33 if(nums[end]==target)return true; 34 return false; 35 36 } 37 }
reference:
http://www.lifeincode.net/programming/leetcode-search-in-rotated-sorted-array-ii-java/
http://www.cnblogs.com/springfor/p/3859525.html
http://blog.csdn.net/linhuanmars/article/details/20588511