Skip to content

Commit 2d95332

Browse files
committed
optimized: search element in 2D matrix in O(n) time
1 parent 737d53c commit 2d95332

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package Lecture14;
2+
3+
public class searchMatrix3 {
4+
5+
public static void main(String[] args) {
6+
7+
int[][] arr = { { 10, 20, 30, 40 },
8+
{ 11, 21, 31, 41 },
9+
{ 12, 22, 32, 42 },
10+
{ 13, 23, 33, 43 } };
11+
12+
System.out.println(staircase(arr, 22)); // true
13+
System.out.println(staircase(arr, 10)); // true
14+
System.out.println(staircase(arr, 42)); // true
15+
System.out.println(staircase(arr, 23)); // true
16+
System.out.println(staircase(arr, 13)); // true
17+
System.out.println(staircase(arr, 2)); // false
18+
19+
}
20+
21+
public static boolean staircase(int[][] arr, int key) {
22+
int row = 0, col = arr.length - 1;
23+
24+
while (row < arr.length && col >= 0) {
25+
if (arr[row][col] == key) {
26+
return true;
27+
} else if (key > arr[row][col]) {
28+
row++;
29+
} else {
30+
col--;
31+
}
32+
}
33+
34+
return false;
35+
}
36+
}

0 commit comments

Comments
 (0)