Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/7407942 to your computer and use it in GitHub Desktop.
Save charlespunk/7407942 to your computer and use it in GitHub Desktop.
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.
public class Solution {
public boolean search(int[] A, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return search(A, target, 0, A.length - 1);
}
public boolean search(int[] A, int target, int begin, int end){
if(begin > end) return false;
int midle = (begin + end) / 2;
if(target == A[midle]) return true;
if(A[midle] == A[begin] && A[midle] == A[end]){
return search(A, target, midle + 1, end) ||
search(A, target, begin, midle - 1);
}
if(A[midle] >= A[begin]){
if(target < A[midle]){
if(target >= A[begin])
return search(A, target, begin, midle - 1);
else return search(A, target, midle + 1, end);
}
else return search(A, target, midle + 1, end);
}
else{
if(target < A[midle])
return search(A, target, begin, midle - 1);
else{
if(target >= A[begin])
return search(A, target, begin, midle - 1);
else return search(A, target, midle + 1, end);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment