
这道题是让我们在二维数组中快速搜索一个数字,这个二维数组各行各列都是按递增顺序排列的,观察题目中给的例子,我们可以发现有两个位置的数字很有特点,左下角和右上角的数,左下角的18,往上所有数变小,往右所有数变大。那么我们就可以和目标数相比较,如果目标数打,就往右搜,如果目标数小,就往上搜。这样就可以判断目标数是否存在。当然我们也可以把起始数放在右上角,往左和往下搜,停止条件设置正确就行。
算法描述:
代码如下:
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return false; int x = matrix.length-1,y = 0;while(x >= 0&& y < matrix[0].length){ if(matrix[x][y] > target) --x; else if(matrix[x][y] < target) ++y; else return true; //当前数就是要找的数 } return false; } }
还有一种解法就是对每一行进行二分查找,即遍历矩阵中的每一行,进行二分查找,时间复杂度为O(mlogn)。上面用分治算法的时间复杂度为O(m+n)。
原文:https://www.cnblogs.com/zhlz/p/10488823.html