Problem
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
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.
Code
bool search_r(int A[], int l,int r, int target) { if(l > r) { return false; } int m = (l + r)/2; if(A[m - 1] > A[l - 1]){ if(target == A[m - 1]) return true; if(target < A[m - 1] && target >= A[l - 1]) r = m - 1; else l = m + 1; return search_r(A,l,r,target); } else if(A[m - 1] < A[l - 1]){ if(target == A[m - 1]) return true; if(target > A[m - 1] && target <= A[r - 1]) l = m + 1; else r = m - 1; return search_r(A,l,r,target); } else{ if(target == A[m - 1]) return true; return (search_r(A,m + 1,r,target) || search_r(A,l,m - 1,target)); } } bool search(int A[], int n, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int l = 1, r = n; bool ret = search_r(A,l,r,target); return ret; }
No comments:
Post a Comment