-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchA2DMarix.java
More file actions
57 lines (45 loc) · 1.47 KB
/
Copy pathSearchA2DMarix.java
File metadata and controls
57 lines (45 loc) · 1.47 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package twodimensionalarray;
public class SearchA2DMarix {
public static boolean searchMatrix(int[][] matrix, int target) {
// top-right
/*
int row = 0, col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) {
System.out.println("Target found at (" + row + ", " + col + ")");
return true;
} else if (target < matrix[row][col]) {
col--;
} else {
row++;
}
}
System.out.println("Target not found");
return false; */
// bottom-left
int row = matrix.length - 1, col = 0;
while (row >= 0 && col < matrix[0].length) {
if (matrix[row][col] == target) {
System.out.println("Found at (" + row + ", " + col + ")");
return true;
} else if (target < matrix[row][col]) {
row--;
} else {
col++;
}
}
System.out.println("Target not found");
return false;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 60}
};
int target = 3;
searchMatrix(matrix, target);
}
}
// Search a 2D Matrix (LeetCode 74)
// https://leetcode.com/problems/search-a-2d-matrix/description/