[LeetCode]Search in Rotated Sorted Array II
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.
思考:在上一题的基础上思考几个边界问题。
[1,3] 3 [1,3] 3
[3,3] 1 [3,1] 3
[1,3,1,1,1] 3
[1,1,1,3,1] 1
class Solution { public: bool search(int A[], int n, int target) { int left=0; int right=n-1; while(left<=right) { int mid=(left+right)>>1; if(A[mid]==target) return true; if(A[mid]==A[left]) { if(A[mid]==A[right]) { left++; right--; } else left=mid+1; } else if(A[mid]>A[left]) { if(A[mid]>=target&&target>=A[left]) right=mid-1; else left=mid+1; } else { if(A[mid]<=target&&target<=A[right]) left=mid+1; else right=mid-1; } }//5 6 7 1 2 3 4 return false; } };