• 搜索区间


    http://www.lintcode.com/zh-cn/problem/search-for-a-range/

    错误点: 1。返回值类型int[],所以return new int[] {-1, -1}, 而不要写 new {-1, -1},后者不精确

         2。在给结果赋值时,考虑到有 [1,1,1,1,1,1]  1 的情况,所以考虑好if语句赋值的先后顺序,清楚的考虑好>,=,<这三种情况对应的赋值方式,然后再合并。

        3. int  a=1,b=2;  不报错

            a=1,b=2  lintcode报错

          

    注意点:  结果返回时, int[] result = new int[2] ,赋值时给result[0] 、[1]赋值即可,不用每次都new新数组返回。

     1  public int[] searchRange(int[] A, int target) {
     2         // write your code here
     3         //if (A == null || A.length == 0) {
     4         if (A.length == 0) {
     5             return new int[] {-1, -1};
     6         }
     7         int[] bound = new int[2];
     8         //左边界确定
     9         int start, end, mid;
    10         start = 0; end = A.length - 1;
    11         while(end - start > 1) {
    12             mid = start + (end - start) / 2;
    13             if (A[mid] >= target) {
    14                 end = mid; 
    15             } else {
    16                 start = mid;
    17             }
    18         }
    19         if (A[start] == target) {
    20             bound[0] = start;
    21         } else if (A[end] == target) {
    22             bound[0] = end;
    23         } else {
    24             bound[0] = bound[1] = -1;
    25             return bound;
    26         }
    27         //右边界确定
    28         start = 0; end = A.length - 1;
    29         while(end - start > 1) {
    30             mid = start + (end - start) / 2;
    31             if (A[mid] <= target) {
    32                 start = mid; 
    33             } else {
    34                 end = mid;
    35             }
    36         }
    37         if (A[end] == target) {
    38             bound[1] = end;
    39         } else if (A[start] == target) {
    40             bound[1] = start;
    41         } else {
    42             bound[0] = bound[1] = -1;
    43             return bound;
    44         }
    45         return bound;
    46     }
    View Code
  • 相关阅读:
    Delphi中WebBrowser控件打开部分网站报"Invalid floating point operation”解决
    delphi中URL的汉字编码
    python手记(11)
    李维对VCL理解的几个错误
    如何配置MYSQL的MASTER---SLAVE复制备份?
    UniDAC连接Embedded MySQL server
    unigui组件中client javascript delphi组件之间的操作
    Delphi中SendMessage使用说明(所有消息说明) good
    iOS面试题
    Windows的MAX_PATH
  • 原文地址:https://www.cnblogs.com/ddcckkk/p/6805568.html
Copyright © 2020-2023  润新知