search a 2D matrix(在二维数组中搜索一个元素)

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;
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8213621.html