Title Requirements:
Follow to "Search in rotated Sorted Array":
What if duplicates is allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given the target was in the array.
Title Address: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
Public classSolution { Public Static BooleanSearchint[] A,inttarget) { intFirst=0,last=a.length-1, Mid; while(first<=Last ) {Mid= (first+last)/2; System.out.println ("Current search scope" +a[first]+ "--" +a[last]+ ", mid=" +A[mid]); if(A[mid]==target)return true; Else if(A[first]<a[mid]) {//left ordered if(target>=a[first]&&target<A[mid]) { Last=mid-1; }Else{ First=mid+1; } }Else if(A[first]>a[mid]) {//Right Order if(target>a[mid]&&target<=A[last]) { First=mid+1; }Else{ Last=mid-1; } }Else{//A[first]==a[mid] if(A[last]>a[mid]) {//Right Order if(target>a[mid]&&target<=A[last]) { First=mid+1; }Else{ Last=mid-1; } }Else if(A[last]<a[mid]) {//left ordered, with the left range the same numberFirst=mid+1; }Else{//cannot be determinedfirst++; Last--; } } } return false; }}
Analysis Ideas:
First of all, refer to the original topic does not repeat the idea, only first==mid when the treatment of different, divided into the following situations:
At the time of First==mid:
A. When last>mid, there must be a right order;
B. When Last<mid, the flip singularity is in the right range, then there must be left ordered, and the left range is the same number.
B. When last=mid, the singular point distribution cannot be determined, then the LAST,MID,FIRST3 is equal to the target, then the last--, first++ to see the next step.
Leetcode:search in rotated Sorted Array II (duplicated)