LeetCode 240. Search a 2D Matrix II

LeetCode 240. Search a 2D Matrix II

Description:

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.

Given target = 20, return false.


分析:

可从二维数组最后一行第一列的数开始与target比较,当matrix[m][n] > target时,m减1,表示该行的数都比target大,不用继续比较该行的数;当matrix[m][n] < target时,n加1,表示该列的数都比target小,不用继续比较该列的数,应比较更大的列;当找到相等的数时,返回true;否则循环结束后返回false。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size() - 1;
int n = 0;
while (m >= 0 && n < matrix[m].size()) {
if (matrix[m][n] == target) return true;
if (matrix[m][n] > target) m--;
else n++;
}
return false;
}
};
------本文结束感谢阅读------