Follow up for "Search in Rotated Sorted Array":算法
What if duplicates are allowed?ide
Would this affect the run-time complexity? How and why?this
Write a function to determine if a given target is in the array.blog
出現相等元素以後會出現一種特殊退化的狀況,即中間元素等於start,end的元素,這樣沒法判斷左邊或者右邊是否出現突增,增減,因此這種狀況下必須遞歸兩邊,算法退化成線性比較。遞歸
1st (3 tries)get
class Solution { public: bool search(int A[], int n, int target) { if(A[0] < A[n-1]) return binary_search(A,0,n-1,target); else return ordinary_search(A,0,n-1,target); } bool binary_search(int A[],int start,int end,int target) { if(start > end) return false; int mid = (start + end)/2; if(A[mid] == target) return true; if(A[mid] > target) { return binary_search(A,start,mid-1,target); } else { return binary_search(A,mid+1,end,target); } } bool ordinary_search(int A[],int start,int end,int target) { if(start > end) return false; int mid = (start + end)/2; if(A[mid] == target) return true; /**this is new**//**test case 1,3,1,1,1 or 1,1,1,3,1 沒法判定3的具體位置**/ if(A[start] == A[mid] && A[mid] == A[end]) { return ordinary_search(A,start,mid-1,target)||ordinary_search(A,mid+1,end,target); } else if(A[start] <= A[mid]) { if(target <= A[mid] && target >= A[start]) { return binary_search(A,start,mid-1,target); } else { return ordinary_search(A,mid+1,end,target); } } else { if(target >= A[mid] && target <= A[end]) { return binary_search(A,mid+1,end,target); } else { return ordinary_search(A,start,mid-1,target); } } } };
2nd (3 tries)it
class Solution { public: bool search(int A[], int n, int target) { //if exists equal so don't know whether left or right is available??? return search(A,0,n-1,target); } bool search(int A[], int start, int end, int target) { if(start > end) return false; int mid = start + (end - start)/2; if( A[mid] == target ) return true; else if( A[mid] > target ) { //two side??? if( A[start] == A[end] ) { return search(A,start,mid-1,target) || search(A,mid+1,end,target); } else { //no rotate,sorted array!!! if( A[start] < A[end] ) { return bsearch(A,start,end,target); } // A[start] > A[end]!!! else { if( A[mid] < A[start] ) { return search(A,start,mid-1,target); } //A[mid] >= A[start] else { if(target >= A[start]) { return bsearch(A,start,mid-1,target); } else { return search(A,mid+1,end,target); } } } } } else { if( A[start] == A[end] ) { return search(A,start,mid-1,target) || search(A,mid+1,end,target); } else { //no rotate,sorted array!!! if( A[start] < A[end] ) { return bsearch(A,start,end,target); } // A[start] > A[end]!!! else { if( A[mid] < A[start] ) { if(target <= A[end]) { return bsearch(A,mid+1,end,target); } else { return search(A,start,mid-1,target); } } //A[mid] >= A[start] else { return search(A,mid+1,end,target); } } } } } //binary search!!! bool bsearch(int A[], int start, int end, int target) { while(start <= end) { int mid = start + (end-start)/2; if(A[mid] == target) return true; else if(A[mid] > target) { end = mid-1; } else { start = mid+1; } } return false; } };