Search for a range
public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = -1;
        result[1] = -1;
        if (nums == null || nums.length < 1) {
            return result;
        }
        int left = 0;
        int right = 0;
        //search for left bound.
        right = nums.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (nums[left] == target) {
            result[0] = left;
        } else if (nums[right] == target) {
            result[0] = right;
        } else {
            result[0] = -1;
            result[1] = -1;
            return result;
        }
        //search for right bound.
        left = result[0];
        right = nums.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (nums[right] == target) {
            result[1] = right;
        } else {
            result[1] = left;
        }
        return result;
    }
}

阅读更多
文章标签: Array Binary Search
个人分类: 刷题 Leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Search for a range

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭