34. Search for a Range**

来源:互联网 发布:网络销售代理产品 编辑:程序博客网 时间:2024/05/22 13:16

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 [] result = {-1,-1};        if (nums.length==0) return result;        int low = 0, high =nums.length-1;        while(low<high){            int mid = low +(high-low)/2;            if(nums[mid]<target) low =mid+1;            else high =mid;        }        if(nums[low]!=target) return result;        else result[0] = low;        high = nums.length-1;        while(low<high){            int mid = low+(high-low)/2+1;            if(nums[mid]>target) high = mid-1;            else low = mid;        }        result[1]=high;        return result;            }
总结:两个binary search, 分别搜寻左右端点。

一个小trick, 在搜寻右端点的时候,mid = low+(high-low)/2+1,使得等式向右偏。否则,如果low =mid,(low+high)/2==mid时,若nums[mid]==target, 陷入死循环。左端点不存在这个问题,因为向左偏。

0 0
原创粉丝点击