forked from xiaoningning/java-algorithm-2010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind2DArray.java
More file actions
39 lines (32 loc) · 924 Bytes
/
find2DArray.java
File metadata and controls
39 lines (32 loc) · 924 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
35
36
37
38
import java.util.Arrays;
/**
* To find a x in a 2D sorted array
*/
public class find2DArray {
public static void main(String[] args) {
int[][] arr = {{15, 20, 40, 85},
{20, 35, 50, 95},
{40, 55, 80, 110},
{70, 80, 95, 120},
{95, 110, 120, 140},
{100, 120, 140, 150}};
System.out.println(Arrays.deepToString(arr));
int target = 80;
find2DArrayNum(arr, target);
}
public static void find2DArrayNum(int[][] n, int x) {
int r = 0;
int c = n[0].length -1;
while( r < n.length && c >= 0){
if(n[r][c] == x){
System.out.println(r + " " + c );
return;
}
else if (n[r][c] < x)
r++;
else // n[r][c] >x
c--;
}
System.out.println("not found");
}
}