Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

 

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

 

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

 

根据上面的条件可以看出,该数组从左往后依次增加。所以可以将二维数组拉长看成一位数组,然后使用二分查找。重点是对于看成一维数组后的位置要对应到二维数组的位置。

 

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix==null||matrix.length==0) return false;
        int m=matrix.length;
        int n=matrix[0].length;
        int left=0,right=m*n-1;   //看成一位数组,然后根据第几个元素转到二维数组的对应位置
        while(left<=right){
            int mid=(left+right)/2;  //mid 表示第几个元素.重点是根据这个中间值找到它对应的行和列
            int mid_value=matrix[mid/n][mid%n];
            if(mid_value==target) return true;
            else if(mid_value>target) right=mid-1;
            else left=mid+1;
        }
        return false;
    }
}

 

相关文章:

  • 2021-05-21
  • 2021-08-12
  • 2022-12-23
  • 2022-01-11
  • 2021-12-19
  • 2021-08-02
  • 2022-01-22
  • 2021-08-28
猜你喜欢
  • 2021-06-23
  • 2021-06-03
  • 2021-12-14
  • 2022-12-23
  • 2021-06-24
  • 2022-12-23
  • 2021-12-03
相关资源
相似解决方案