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

Search for a Range ——LeetCode

时间:2015-06-08 08:24:59      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

 

题目大意:给定一个排序好的数组,找到指定数的起始范围,如果不存在返回[-1,-1];

解题思路:要求O(lgN)时间复杂度,二分查找。

    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[2];
        if(nums==null||nums.length==0){
            return res;
        }
        res[0]=getLow(nums,target,0,nums.length-1);
        res[1]=getHigh(nums,target,0,nums.length-1);
        return res;
    }
    int getLow(int[] nums,int target,int low,int high){
        int mid=(low+high)>>1;
        if(low>high){
            return -1;
        }
        if(low==high){
            return nums[low]==target?low:-1;
        }
        if(nums[mid]==target){
            return getLow(nums,target,low,mid);
        }
        if(nums[mid]<target){
            low=mid+1;
            return getLow(nums,target,low,high);
        }else{
            high=mid-1;
            return getLow(nums,target,low,high);
        }
    }
    int getHigh(int[] nums,int target,int low,int high){
         int mid=(low+high)>>1;
         if(low>high){
             return -1;
         }
        if(low==high){
            return nums[low]==target?low:-1;
        }
        if(nums[mid]==target){
            int tmp=getHigh(nums,target,mid+1,high);
            int max=Math.max(tmp,mid);
            return max;
        }
        if(nums[mid]<target){
            low=mid+1;
            return getHigh(nums,target,low,high);
        }else{
            high=mid-1;
            return getHigh(nums,target,low,high);
        }
    }

 

Search for a Range ——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4560008.html

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