34 Search for a Range

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

分析&& 代码

这个居然是最近google家的面经:3,真的是人和人运气不同

看了一眼discuss也没什么特别的好做法,就是两边Binary search找到最左和最右,这题是返回左右index,面经是返回个数,反正都是一个道理

public int getNum(int[] arr, int target) {
    if(arr.length == 0) {
        return -1;
    }
    return findRight(arr, target) - findLeft(arr, target) + 1;
}

private int findLeft(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;
    while(left <= right) {
        int mid = left + (right - left) / 2;
        if(arr[mid] == target) {
            if(mid != 0 && arr[mid - 1] == target) {
                right = mid - 1;
            } else {
                return mid;
            }
        } else if(arr[mid] > target) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return -1;
}

private int findRight(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;
    while(left <= right) {
        int mid = left + (right - left) / 2;
        if(arr[mid] == target) {
            if(mid != 0 && arr[mid + 1] == target) {
                left = mid + 1;
            } else {
                return mid;
            }
        } else if(arr[mid] > target) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return -1;
}

反正都O(logn)

results matching ""

    No results matching ""