Search for a Range

来源:互联网 发布:印度人看中国知乎 编辑:程序博客网 时间:2024/05/16 03:00

Q:

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


Solution:

3 times binary search.

public class Solution {    public int[] searchRange(int[] A, int target) {        int[] ret = {-1, -1};        int left = 0;        int right = A.length - 1;        int mid = (left + right) / 2;        while (left <= right) {            if (target < A[mid])                right = mid - 1;            else if (target == A[mid])                break;            else                left = mid + 1;            mid = (left + right) / 2;        }        if (A[mid] != target)            return ret;        int left1 = left;        int right1 = mid;        int mid1 = (left1 + right1) / 2;        while (left1 <= right1) {            if (target == A[mid1])                right1 = mid1 - 1;            else                left1 = mid1 + 1;            mid1 = (left1 + right1) / 2;        }        ret[0] = left1;        int left2 = mid;        int right2 = right;        int mid2 = (left2 + right2) / 2;        while (left2 <= right2) {            if (target == A[mid2])                left2 = mid2 + 1;            else                right2 = mid2 - 1;            mid2 = (left2 + right2) / 2;        }        ret[1] = right2;        return ret;    }}


0 0
原创粉丝点击