二刷34. Search for a Range

出 bug的地方:

  • 一开始没判断nums == null || nums.length == 0
  • 二分搜索的时候有可能start就没找到,这个时候start=first会导致start = -1后面你用nums[start]就会数组越界. 所以搜索完start的时候你要记得判断一下start == -1?如果等于说明nums里面没有target你要直接返回[-1,-1]
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0){
            return new int[]{-1,-1};
        }
        //[1]
        //0
        int first = -1;
        int 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;
        } 
        start = first;
        end = nums.length - 1;
        if (start == -1){
            return new int[]{-1,-1};
        }
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] <= target){
                start = mid;
            } else {
                end = mid;
            }
        }
        if (nums[end] == target){
            last = end;
        } else if (nums[start] == target){
            last = start;
        }
        return new int[]{first, last};
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/82c41423baff
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞