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.

Solution:

  1. public class Solution {
  2. public boolean search(int[] A, int target) {
  3. return bsearch(A, target, 0, A.length - 1);
  4. }
  5. private boolean bsearch(int[] A, int target, int lo, int hi) {
  6. if (lo > hi) {
  7. return false;
  8. }
  9. int mid = lo + (hi - lo) / 2;
  10. if (A[mid] == target) {
  11. return true;
  12. }
  13. if (A[lo] < A[mid]) {
  14. if (target >= A[lo] && target < A[mid]) {
  15. return bsearch(A, target, lo, mid - 1);
  16. } else {
  17. return bsearch(A, target, mid + 1, hi);
  18. }
  19. } else if (A[lo] > A[mid]) {
  20. if (target > A[mid] && target <= A[hi]) {
  21. return bsearch(A, target, mid + 1, hi);
  22. } else {
  23. return bsearch(A, target, lo, mid - 1);
  24. }
  25. } else {
  26. return bsearch(A, target, lo + 1, hi);
  27. }
  28. }
  29. }