leetcode:Search for a Range

来源:互联网 发布:百度世界大会 知乎 编辑:程序博客网 时间:2024/05/18 23:54

二分搜索算法的进化版:

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

我的细节处理的不好,这是国外大神的解法


public class Solution {    private int binarySearch(int[] A, int target) {        if(A.length == 0)            return -1;        int right = A.length - 1;        int left = 0;        while(left<=right) {            int middle = left + (right-left)/2;            if(target > A[middle])                left = middle + 1;            else if(target < A[middle])                right = middle - 1;            else                 return middle;        }        return -1;    }    private int leftMost(int[] A, int left, int right, int target){        while(left <= right) {            int middle = left + (right - left)/2;            if(target == A[middle]) {                if(middle != 0 && A[middle] == A[middle - 1])                    right = middle - 1;                else {                    return middle;                }            } else {                left = middle + 1;            }        }        return -1;    }    private int rightMost(int[] A, int left, int right, int target) {        while(left <= right) {            int middle = left + (right - left)/2;            if(target == A[middle]){                if(middle != (A.length - 1) && A[middle] == A[middle + 1])                    left = middle + 1;                else {                     return middle;                }            } else {                right = middle - 1;            }        }        return -1;    }    public int[] searchRange(int[] A, int target) {        int anchor = binarySearch(A, target);        int left = -1;        int right = -1;        if(anchor != -1) {            left = anchor;            right = anchor;            if(anchor != 0 && A[anchor] == A[anchor -1]) {                //lets find the left most index                left = leftMost(A, 0, anchor - 1, target);            }             if(anchor != (A.length-1) && A[anchor] == A[anchor+1]) {                //lets find the right most index                right = rightMost(A, anchor + 1, A.length - 1, target);            }        }        return new int[] {left, right};    }}


0 0
原创粉丝点击