publicbooleansearchMatrix(int[][] matrix, int target){ if (matrix == null || matrix.length == 0) { returnfalse; } int row = matrix.length, col = matrix[0].length; for (int r = 0; r < row; ++r) { for (int c = 0; c < col; ++c) { if (matrix[r][c] == target) { returntrue; } } } returnfalse; }
Time: $O(MN)$ Space: $O(1)$
Starting From Corner
Note:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicbooleansearchMatrix(int[][] matrix, int target){ if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { returnfalse; } int row = matrix.length, col = matrix[0].length; int r = 0, c = col - 1; while (r < row && c >= 0) { if (matrix[r][c] == target) returntrue; if (target < matrix[r][c]) { // go left c -= 1; } else { // go down r += 1; } } returnfalse; }
Time: $O(M + N)$ Space: $O(1)$
Binary Search
Learn the conversion between matrix indices and its corresponding list’s index.
publicbooleansearchMatrix(int[][] matrix, int target){ if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { returnfalse; } int row = matrix.length, col = matrix[0].length; int lo = 0, hi = row * col - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; // convert to row and column int r = mid / col; int c = mid % col; if (matrix[r][c] == target) returntrue; if (matrix[r][c] > target) { hi = mid - 1; } else { lo = mid + 1; } } returnfalse; }
Lower Bound Version:
Remember to check boundary before returning.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicbooleansearchMatrix(int[][] matrix, int target){ if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { returnfalse; } int row = matrix.length, col = matrix[0].length; int lo = 0, hi = row * col - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int r = mid / col; int c = mid % col; if (matrix[r][c] >= target) { hi = mid - 1; } else { lo = mid + 1; } } // remember to check boundary return (lo < row * col) && matrix[lo / col][lo % col] == target; }