Search for a Range

Given an array of integers sorted in ascending order, 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 int[] searchRange(int[] nums, int target) {
        int length = nums.length;
        int low = 0;
        int high = length-1;
        int start,end= 0;
        while (low<=high){
            int middle = (low+high)/2;
            if (nums[middle]==target){
                start = middle;
                end = middle;
                while (start>=0&&nums[start]==target){
                    start--;
                }
                start++;
                while (end<length&&nums[end]==target){
                    end++;
                }
                end--;
                return new int[]{start,end};
            }
            else if (nums[middle]>target){
                high=middle-1;
            }
            else if (nums[middle]<target){
                low = middle+1;
            }
        }
        return new int[]{-1, -1};
    }
posted @ 2018-01-15 14:46  binryang  阅读(114)  评论(0编辑  收藏  举报