LeetCode Solution-74
Posted littledy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Solution-74相关的知识,希望对你有一定的参考价值。
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:
(ullet)Integers in each row are sorted from left to right.
(ullet)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
以上是关于LeetCode Solution-74的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段