IncredibleThings

导航

LeetCode-Search for a Range

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

 

posted on 2016-08-06 02:30  IncredibleThings  阅读(118)  评论(0编辑  收藏  举报