题目链接:二维数组中的查找
思路:二维矩阵数值分布特点是左上角高,右下角低。如果从最高处或最低处开始搜索,那么搜寻路径会很多。而从矩阵右上角开始搜索的话,可以发现,右上角的左边都是递减,下边是递增,那么,从左上角出发,比target大时,就走左边;比target小时就走下边,直到找到target或者走出矩阵范围。同理从左下角出发也可以。
代码:
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix.length == 0) return false;
for(int x = 0, y = matrix[x].length-1; x>=0 && y>=0 && x<matrix.length && y<matrix[x].length;){
if(matrix[x][y] == target) return true;
if(matrix[x][y] < target) x ++;
else y --;
}
return false;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:44 MB, 在所有 Java 提交中击败了90.04%的用户