forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchA2dMatrix.java
More file actions
34 lines (32 loc) · 860 Bytes
/
SearchA2dMatrix.java
File metadata and controls
34 lines (32 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.examplehub.leetcode.middle;
/** https://leetcode.com/problems/search-a-2d-matrix/ */
public class SearchA2dMatrix {
public static boolean solution1(int[][] matrix, int target) {
for (int[] rows : matrix) {
for (int item : rows) {
if (target == item) {
return true;
}
}
}
return false;
}
public static boolean solution2(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int columns = matrix[0].length;
for (int row = 0, col = columns - 1; row < rows && col >= 0; ) {
int number = matrix[row][col];
if (number == target) {
return true;
} else if (number < target) {
row++;
} else {
col--;
}
}
return false;
}
}