34. Search for a Range

一句话思路:新建数组存储位置,输出数组

一刷报错:

  1. 是nums[mid],nums[start/end]和target的关系,不是mid start end和target的关系
  2. 右边界 start end调换后,不对

二刷改了小格式之后ac:

  1. 数组定义时,举例出元素的时候没有等号。return new int[]  {-1, -1};
  2. 是start end=bound[0,1],不是target=bound[0,1]。别粗心。

总结:bound[0],是从前往后查找的,从前开始查。

         bound[1],是从后往前查找的,从后开始查。

风格上:

  1. 数组里面的数之间要有空格。
  2. 每次声明一个变量 int a; 

            intb;

  1. if 后面要加空格!!
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        
        int start;
        int end;
        int mid;
        int []bound = new int[2];
        
        //search for the left bound
        start = 0;
        end = nums.length - 1;
        while (start + 1 < end) {
            mid = start + (end - start) / 2;
            if (nums[mid] == target) {
                end = mid;
            }
            if (nums[mid] < target) {
                start = mid;
            }
            if (nums[mid] > target) {
                end = mid;
            }
        }
        //System.out.println("start1="+start);
        //System.out.println("end1="+end);
        
        if (nums[start] == target) {
            bound[0] = start;
        }
        else if (nums[end] == target) {
            bound[0] = end;
        }
        else {
            bound[0] = -1;
            bound[1] = -1;
        }
        //System.out.println("bound[0]="+bound[0]);
        
        //search for the right bound
        end = 0;
        start = nums.length - 1;
        while (end + 1 < start) {
            mid = end + (start - end) / 2;
            if (nums[mid] == target) {
                end = mid;
            }
            if (nums[mid] < target) {
                end = mid;
            }
            if (nums[mid] > target) {
                start = mid;
            }
        }
        //System.out.println("start2="+start);
        //System.out.println("end2="+end);
        
        if (nums[start] == target) {
            bound[1] = start;
        }
        else if (nums[end] == target) {
            bound[1] = end;
        }
        else {
            bound[0] = -1;
            bound[1] = -1;
        }
        //System.out.println("bound[1]="+bound[1]);
        
        return bound;
    }
}

 

posted @ 2017-11-22 08:52  苗妙苗  阅读(162)  评论(0编辑  收藏  举报