Search for a Range

来源:互联网 发布:网站排名优化 编辑:程序博客网 时间:2024/05/15 03:29

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].

当search到target的时候,为了寻找左下标,继续search左半边;同理search右半边来寻找右下标。

    public int[] searchRange(int[] A, int target) {        int left = -1;        int right = -1;                int low = 0, high = A.length-1;        // search left        while(low <= high) {            int m = low + (high-low)/2;            if (A[m] == target) {                left = m;                high = m-1;            } else if (A[m] < target) {                low = m+1;            } else {                high = m-1;            }        }        low = 0; high = A.length-1;        // search right        while(low <= high) {            int m = low + (high-low)/2;            if (A[m] == target) {                right = m;                low = m+1;            } else if (A[m] < target) {                low = m+1;            } else {                high = m-1;            }        }                int[] result = new int[2];        result[0] = left;        result[1] = right;        return result;    }


0 0
原创粉丝点击