Top 100
Search a 2D Matrix II
- Problem
- LC 240
- File
- top100_LC240SearchA2DMatrixII.java
- Path
- pkg5leetcode/top100/top100_LC240SearchA2DMatrixII.java
- Package
- pkg5leetcode.top100
- Command
- java pkg5leetcode/top100/top100_LC240SearchA2DMatrixII.java
- Approach
- Start top-right; move left or down based on comparison.
- Complexity
- Time O(m+n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.top100;2 3/*4 * Search a 2D Matrix II | LC 2405 * APPROACH: Start top-right; move left or down based on comparison.6 * COMPLEXITY: Time O(m+n), Space O(1)7 */8public class top100_LC240SearchA2DMatrixII {9 static boolean searchMatrix(int[][] matrix, int target) {10 int r = 0, c = matrix[0].length - 1;11 while (r < matrix.length && c >= 0) {12 if (matrix[r][c] == target) return true;13 if (matrix[r][c] > target) c--;14 else r++;15 }16 return false;17 }18 19 public static void main(String[] args) {20 int[][] m = {{1,4,7,11,15},{10,11,16,20,23},{23,30,34,60}};21 check(searchMatrix(m, 5), "case1");22 check(!searchMatrix(m, 13), "case2");23 System.out.println("all tests passed");24 }25 26 static void check(boolean cond, String name) {27 if (!cond) throw new AssertionError("FAILED: " + name);28 System.out.println(" PASS " + name);29 }30}