34. Search for a Range

Medium
最早接触刷题刚学Binary Search那时候的习题,现在还是印象深刻,九章的老师讲得很好这一部分.

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0){
            return new int[]{-1, -1};
        }    
        int first = -1, last = -1;
        int start = 0;
        int end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] >= target){
                end = mid;
            } else {
                start = mid;
            }
        }
        if (nums[start] == target){
            first = start; 
        } else if (nums[end] == target){
            first = end;
        } 
        if (first == -1){
            return new int[]{-1, -1};
        }
        start = first;
        end = nums.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] > target){
                end = mid;
            } else {
                start = mid;
            }
        }
        if (nums[end] == target){
            last = end;
        } else if (nums[start] == target){
            last = start;
        }
        return new int[]{first, last};
    }
}

你可能感兴趣的:(34. Search for a Range)