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

LeetCode-Search for a Range

时间:2016-08-06 06:58:51      阅读:136      评论: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].
public class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums==null || nums.length==0){
            return null;
        }
        int[] res={-1, -1};
        int len=nums.length;
        
        int low=0;
        int high=len-1;
        int pos=0;
        while(low<=high){
            int mid=low+(high-low)/2;
            pos=mid;
            if(nums[mid]>target){
                high=mid-1;
            }
            else if(nums[mid]< target){
                low=mid+1;
            }
            else{
                res[0]=pos;
                res[1]=pos;
                break;
            }
        }
        if(nums[pos]!=target){
            return res;
        }
        //find the right boundary
        int newLow=pos;
        int newHigh=len-1;
        while(newLow<=newHigh){
            int newMid=newLow+(newHigh-newLow)/2;
            if(nums[newMid]==target){
                newLow=newMid+1;
            }
            else{
                newHigh=newMid-1;
            }
        }
        res[1]=newHigh;
        //find the left boundary
        newLow=0;
        newHigh=pos;
        while(newLow <= newHigh){
            int newMid=newLow+(newHigh-newLow)/2;
            if(nums[newMid] == target){
                newHigh=newMid-1;
            }
            else{
                newLow=newMid+1;
            }
        }
        res[0]=newLow;
        return res;
    }
}

 

LeetCode-Search for a Range

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5743212.html

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