编写一个高效的算法来搜索?m?x?n
?矩阵?matrix
?中的一个目标值?target
?。该矩阵具有以下特性:
示例 1:
输入: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]], target = 5 输出:true
示例 2:
输入: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]], target = 20 输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109?<= matrix[i][j] <= 109
-109?<= target <= 109
。。。广度优先遍历超时了。。。。
这题很简单,写博客单纯是为了记录下,看代码很好理解
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int[][] plants = matrix;
if(plants.length==0) return false;
int row = plants.length;
int col = plants[0].length;
int r = row-1;
int c = 0;
while(r<row && r>=0 && c>=0 && c<col){
if(plants[r][c]==target) return true;
if(plants[r][0]>target) r--;
else{
if(plants[r][c]<target) c++;
else if(plants[r][c] == target) return true;
else if(plants[r][c] > target) r--;
}
}
return false;
}
}