zoukankan      html  css  js  c++  java
  • Search In Sorted Matrix I

    Given a 2D matrix that contains integers only, which each row is sorted in an ascending order. The first element of next row is larger than (or equal to) the last element of previous row.

    Given a target number, returning the position that the target locates within the matrix. If the target number does not exist in the matrix, return {-1, -1}.

    Assumptions:

    • The given matrix is not null, and has size of N * M, where N >= 0 and M >= 0.

    Examples:

    matrix = { {1, 2, 3}, {4, 5, 7}, {8, 9, 10} }

    target = 7, return {1, 2}

    target = 6, return {-1, -1} to represent the target number does not exist in the matrix.

     
     1 public int[] search(int[][] matrix, int target) {
     2     // Write your solution here
     3     if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
     4         return new int[] {-1,-1} ; 
     5     }
     6     
     7     int n = matrix.length, m = matrix[0].length ; 
     8     int left = 0 , right = n*m-1 ; 
     9     int[] res = {-1,-1} ; 
    10     /*
    11         rowIndex: index/m 
    12       colIndex: index%m 
    13     */
    14     //this is classical binary search: <= +1 -1 
    15     while(left <= right){
    16         int mid = left + (right - left )/2 ; 
    17       int rowIndex = mid/m ; // /0 corner case already considered
    18       int colIndex = mid%m ; 
    19       if(matrix[rowIndex][colIndex] == target){
    20           res[0] = rowIndex ; 
    21         res[1] = colIndex ; 
    22         return res ; 
    23       } else if(matrix[rowIndex][colIndex] < target){
    24           left = mid + 1 ; 
    25       } else {
    26           right = mid - 1 ; 
    27       }
    28     }
    29     return res ; 
    30   }
  • 相关阅读:
    微信小程序
    如何在微信小程序中使用骨架屏
    Nlog打印日志到Influxdb数据库
    C#通过模板导出Word的两种方法(超简单)
    VS2019制作的安装包,默认安装到C盘快捷方式无法打开
    orcale数据库还原备份
    Thread 类创建线程
    Quartz.NET
    DataTable ,使用详细。
    Unity3D 学习
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8468524.html
Copyright © 2011-2022 走看看