Leetcode 240. 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.
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,时间复杂度
。
Q1:为什么往下走以后不需要考虑往右走的情况?
A1:如下图(只是一个局部),比如target为20,当前走到了22的位置,那么这时候他选择往左走走到16,再往下走走到17,它不需要往右走去检查24,因为24这个位置的数根据题意必然大于22,所以不需要考虑。向左走相当于排除了一整列,所以没有必要再往右走
代码
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size()<1){
return false;
}
int n=matrix.size();
int m=matrix[0].size();
int x=0;
int y=m-1;
while(x<n && y>=0){
if(matrix[x][y]>target){
y--;
}else if(matrix[x][y]<target){
x++;
}else{
return true;
}
}
return false;
}
};