Skip to content

Commit efd14ca

Browse files
realDuYuanChaogithub-actions
andauthored
search a 2d matrix (examplehub#128)
* search a 2d matrix * Formatted with Google Java Formatter Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 27a03f6 commit efd14ca

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)