题目:
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:
现有矩阵 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。
给定 target = 20,返回 false。
思路:
先在数组中找一个左下角的数字作为参照数字,然后将参照数字与目标数字进行比较,
1、如果参照数字和目标数字相等返回true
2、如果参照数字小于目标数字,将参照数字的列加1
3、如果参照数字大于目标数字,将参照数字的行减1
代码实现
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length==0){
return false;
}
int row=matrix.length;
int col=matrix[0].length;
int x=matrix.length-1;
int y=0;
while(x>=0&&y<col){
if(matrix[x][y]==target){ //如果参照数字和目标数字相等则返回true
return true;
}else if(matrix[x][y]<target){
y++; //将参照数字的列加1
}else{
x--;
}
}
return false; //如果跳出while循环则说明没有找到
}
}