LeetCode240 Search a 2D Matrix II
题目
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.
For 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
分析
由于每行每列都是有序的,所以可以使得在最大的一行最小的一列开始搜寻或者最大的一列最小的一行开始搜索,判断该数和目标数的大小关系来确定上下左右移动,使得时间复杂度为O(n)。
代码
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
if (!n) return false;
int m = matrix[0].size();
int i = n-1;
int j = 0;
while (j < m && i >= 0) {
if (matrix[i][j] == target) return true;
if (matrix[i][j] > target) i--;
else j++;
}
return false;
}
};
附
题目地址:
LeetCode240