码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Solution-74

时间:2020-02-01 10:28:11      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:follow   注意   否则   following   value   sort   row   this   sea   

74. 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:
\(\bullet\)Integers in each row are sorted from left to right.
\(\bullet\)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 \times n\)维矩阵转换为数组:matrix[x][y] \(\Rightarrow\) a[x*n+y];
数组转换为\(m \times 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

LeetCode Solution-74

标签:follow   注意   否则   following   value   sort   row   this   sea   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12247577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!