[leedcode 81] 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.

public class Solution {
    public boolean search(int[] nums, int target) {
        //注意利用本题的规律进行判断:
        //nums[0]是重点,它是前半段的最小值,后半段的最大值,因此mid需要与它判断大小,进而区分mid落在哪个范围
        //中值和start判断,如果大于start,说明start到mid是递增序列,只要判断target是否在这区间即可
        //如果小于start,说明mid到end是递增序列,只要判断target是否在这个区间即可
        //如果中值等于start(暗含nums[start]不等于target),因此此时start++;
        return findSearch(nums,0,nums.length-1,target);
    }
    public boolean findSearch(int[] nums,int start,int end,int target){
        if(start>end){
            return false;
        }
        int mid=(start+end)/2;
        if(nums[mid]==target) return true;
        if(nums[mid]>nums[start]){
            if(target<nums[mid]&&target>=nums[start]){
                end=mid-1;
            }else{
                start=mid+1;
            }
        }else if(nums[mid]<nums[start]){
            if(target>nums[mid]&&target<=nums[end]){
                start=mid+1;
            }else{
                end=mid-1;
            }
        }else start++;////////
         return findSearch(nums,start,end,target);
    }
}

 

你可能感兴趣的:(search)