码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 81] Search in Rotated Sorted Array II

时间:2015-07-15 12:58:41      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }
}

 

[leedcode 81] Search in Rotated Sorted Array II

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4647858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!