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.
思路和find minmum差不多,需要考虑一下target的取值,以及重复元素的问题,写的时候有点乱,所以代码可能有点冗余,不过基本思想应该是没什么问题的:
public boolean search(int[] nums, int target) { int begin=0,end=nums.length-1; while(begin<end){ int mid=(begin+end)/2; if(nums[mid]==target) return true; if(target<nums[mid]){ if(nums[mid]>nums[begin]){ if(target>=nums[begin]) end=mid-1; else begin=mid+1; } else if(nums[mid]==nums[begin]) begin+=1; else{ begin+=1; end-=1; } } else{ if(nums[mid]<nums[end]){ if(target<=nums[end]) begin=mid+1; else end=mid-1; } else if(nums[mid]==nums[end]) end-=1; else{ end-=1; begin+=1; } } } return false; }