74. Search a 2D Matrix

Problem:

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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

思路
将二维矩阵转化为一位数组,使用二分查找即可。
转换公式:
(m imes n)维矩阵转换为数组:matrix[x][y] (Rightarrow) a[x*n+y];
数组转换为(m imes n)维矩阵:a[x] (Rightarrow) matrix[x/n][x%n];

Solution:

bool searchMatrix(vector<vector<int>>& matrix, int target) {
    if (matrix.size() == 0 || matrix[0].size() == 0)     
        return false;
    int m = matrix.size(), n = matrix[0].size();    
    /*注意一定要先判断矩阵的行和列是否为0,否则会报错:runtime error: reference binding to null pointer of type 'struct value_type' (stl_vector.h)
    产生此问题的原因是若列为0,则matrix[0]无法引用*/

    int l = 0, r = m * n - 1;
    while (l != r) {
        int mid = l + (r - l) / 2;
        if (matrix[mid/n][mid%n] < target)
            l = mid + 1;
        else
            r = mid;
    }
    return matrix[r/n][r%n] == target;
}

性能
Runtime: 8 ms  Memory Usage: 9.9 MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12247577.html