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   }
  • 相关阅读:
    PHP使用数据库永久连接方式操作MySQL的是与非
    php生成xml文件
    Ruby学习之类
    新增题目功能模块总结
    Ruby学习之类2
    smarty section循环成两列的问题
    jQuery validate插件初探
    Zend Framework学习之Zend_Config
    Zend Framework学习之Zend_Loader动态加载文件和类
    JS 删除字符串最后一个字符的方法
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8468524.html
Copyright © 2011-2022 走看看