classSolution { publicbooleanfindNumberIn2DArray(int[][] matrix, int target) { inti= matrix.length - 1, j = 0; while (i >= 0 && j < matrix[0].length) { if (matrix[i][j] > target) --i; elseif (matrix[i][j] < target) ++j; elsereturntrue; } returnfalse; } }
时间复杂度:$O(m + n)$
空间复杂度:$O(1)$
方法二:二分查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicbooleanfindNumberIn2DArray(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0) returnfalse; intm= matrix.length, n = matrix[0].length; for (inti=0; i < m; ++i) { intleft=0, right = n - 1; while (left < right) { intmid= left + right >> 1; if (matrix[i][mid] >= target) right = mid; else left = mid + 1; } if (matrix[i][left] == target) returntrue; } returnfalse; } }