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 { /** * param A : an integer ratated sorted array and duplicates are allowed * param target : an integer to be search * return : a boolean */ public boolean search(int[] A, int target) { // write your code here if(A == null || A.length == 0) return false; int left = 0; int right = A.length - 1; return search(A, target, left, right); } public boolean search(int[] A, int target, int left, int right){ if(left > right) return false; if(left == right){ if(A[left] == target) return true; else return false; } int mid = left + (right - left) / 2; if(A[mid] == target) return true; if(A[mid] > target){ if(A[mid] > A[left]){ boolean flag1 = search(A, target, left, mid - 1); boolean flag2 = search(A, target, mid + 1, right); if(!flag1 && !flag2) return false; else if(!flag1) return flag2; else return flag1; } else if(A[mid] < A[left]){ return search(A, target, left, mid - 1); } else{ return search(A, target, left + 1, right); } } else{ if(A[mid] > A[left]){ return search(A, target, mid + 1, right); } else if(A[mid] < A[left]){ boolean flag1 = search(A, target, left, mid - 1); boolean flag2 = search(A, target, mid + 1, right); if(!flag1 && !flag2) return false; else if(!flag1) return flag2; else return flag1; } else{ return search(A, target, left + 1, right); } } } }
时间: 2024-10-09 20:58:36