关闭

Search for a range

标签: ArrayBinary Search
134人阅读 评论(0) 收藏 举报
分类:
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;
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:25949次
    • 积分:2340
    • 等级:
    • 排名:第15896名
    • 原创:214篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条