LeetCode 74 Search a 2D Matrix（搜索2D矩阵）

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## LeetCode 74 Search a 2D Matrix（搜索2D矩阵）

nomasp 2016-03-01 23:23:31 浏览298

## 翻译

``````写一个高效算法用于在一个m x n的矩阵中查找一个值。

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

## 原文

``````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.``````

## 分析

``````bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix[0][0] > target) return false;
for (int i = 0; i < matrix.size(); ) {
for (int j = 0; j < matrix[i].size(); ) {
if (i == matrix.size() - 1 && matrix[i][j] < target) {
if (j >= matrix[i].size()) return false;
j += 1;
if (matrix[i][j] > target) return false;
}
else if (matrix[i][j] < target && matrix[i+1][j] > target) {
j += 1;
if (j >= matrix[i].size()) return false;
if (matrix[i][j] > target) return false;
}
else if (matrix[i][j] < target && matrix[i + 1][j] <= target) {
i += 1;
}
else if (matrix[i][j] == target) {
return true;
}
if (i == matrix.size() - 1 && j == matrix[i].size() ) {
return false;
}
}
}
return false;
}``````

nomasp
+ 关注

corcosa 10384人浏览