forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchMatrix.java
93 lines (71 loc) · 2.23 KB
/
SearchMatrix.java
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package misc;
public class SearchMatrix {
/*
* Search (find position of) a given key in 2D matrix. All rows and columns are sorted.
*
* Runtime Complexity:
* Linear, O(m+n) where 'm' is number of rows and 'n' is number of columns.
*
* Memory Complexity:
* Constant, O(1).
*
*
* */
protected static class Pair<K, V> {
private K first;
private V second;
public static <K, V> Pair<K, V> createPair(K element0, V element1) {
return new Pair<K, V>(element0, element1);
}
public Pair(K first, V second) {
this.first = first;
this.second = second;
}
public K getFirst() {
return first;
}
public V getSecond() {
return second;
}
}
protected static Pair searchInMatrix(int matrix[][],
int value) {
int M = matrix.length; //rows
int N = matrix[0].length; // columns
// Let's start searching from top right.
// Alternatively, searching from bottom left
// i.e. matrix[M-1][0] can also work.
int i = 0, j = N - 1;
while (i < M && j >= 0) {
if (matrix[i][j] == value) {
return new Pair(i, j);
} else if (value < matrix[i][j]) {
// search left
--j;
} else {
// search down.
++i;
}
}
return new Pair(-1, -1);
}
protected static void verifySearch(int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[0].length; ++j) {
System.out.println("Verifying at " + i + ", " + j);
Pair val_loc = searchInMatrix(matrix, matrix[i][j]);
assert ((int) val_loc.first == i);
assert ((int) val_loc.second == j);
}
}
}
public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 5, 45, 80, 81},
{6, 7, 48, 82, 83},
{20, 22, 49, 85, 86},
{21, 23, 50, 90, 92}
};
verifySearch(matrix);
}
}