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.
题意:查询给定目标值是否在数组中,是search in rotated sorted array的扩展。
思路:因为是上一题的扩展,所以很正常的想到,上题的思路,在本题是否合适。结果发现不能强行的套上去。如:1,1,3,1,target=3,若是按照原来的解法,则应该是左边有序,然而不行;若是if条件判断中间等号,为右边有序,也显然不对。参考了Grandyang的博客才知道,只需在判断上加上判断中间值是否等于最右端值,若是,hi向左移动一个,直到不相等。这样就可以继续保持上题的解法了,具体代码如下:
1 class Solution { 2 public: 3 bool search(int A[], int n, int target) 4 { 5 if(n==0) return false; 6 int lo=0,hi=n-1; 7 while(lo<=hi) 8 { 9 int mid=(lo+hi)/2; 10 if(A[mid]==target) 11 return true; 12 else if(A[mid]<A[hi]) 13 { 14 if(A[mid]<target&&A[hi]>=target) 15 lo=mid+1; 16 else 17 hi=mid-1; 18 } 19 else if(A[mid]>A[hi]) 20 { 21 if(A[lo]<=target&&A[mid]>target) 22 hi=mid-1; 23 else 24 lo=mid+1; 25 } 26 else //重点理解 27 hi--; 28 } 29 return false; 30 } 31 };