File tree Expand file tree Collapse file tree
main/java/com/examplehub/leetcode/middle
test/java/com/examplehub/leetcode/middle Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .examplehub .leetcode .middle ;
2+
3+ /** https://leetcode.com/problems/search-a-2d-matrix/ */
4+ public class SearchA2dMatrix {
5+ public static boolean solution1 (int [][] matrix , int target ) {
6+ for (int [] rows : matrix ) {
7+ for (int item : rows ) {
8+ if (target == item ) {
9+ return true ;
10+ }
11+ }
12+ }
13+ return false ;
14+ }
15+
16+ public static boolean solution2 (int [][] matrix , int target ) {
17+ if (matrix == null || matrix .length == 0 || matrix [0 ].length == 0 ) {
18+ return false ;
19+ }
20+ int rows = matrix .length ;
21+ int columns = matrix [0 ].length ;
22+ for (int row = 0 , col = columns - 1 ; row < rows && col >= 0 ; ) {
23+ int number = matrix [row ][col ];
24+ if (number == target ) {
25+ return true ;
26+ } else if (number < target ) {
27+ row ++;
28+ } else {
29+ col --;
30+ }
31+ }
32+ return false ;
33+ }
34+ }
Original file line number Diff line number Diff line change 1+ package com .examplehub .leetcode .middle ;
2+
3+ import static org .junit .jupiter .api .Assertions .*;
4+
5+ import org .junit .jupiter .api .Test ;
6+
7+ class SearchA2dMatrixTest {
8+ @ Test
9+ void testSolution1 () {
10+ int [][] matrix = {
11+ {1 , 3 , 5 , 7 },
12+ {10 , 11 , 16 , 20 },
13+ {23 , 30 , 34 , 60 }
14+ };
15+ assertTrue (SearchA2dMatrix .solution1 (matrix , 3 ));
16+ assertFalse (SearchA2dMatrix .solution1 (matrix , 13 ));
17+ }
18+
19+ @ Test
20+ void testSolution2 () {
21+ int [][] matrix = {
22+ {1 , 3 , 5 , 7 },
23+ {10 , 11 , 16 , 20 },
24+ {23 , 30 , 34 , 60 }
25+ };
26+ assertTrue (SearchA2dMatrix .solution2 (matrix , 3 ));
27+ assertFalse (SearchA2dMatrix .solution2 (matrix , 13 ));
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments