-
Notifications
You must be signed in to change notification settings - Fork 1
/
240. Search a 2D Matrix II.java
80 lines (72 loc) · 1.95 KB
/
240. Search a 2D Matrix II.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
//BINARY SEARCH APPROACH - OPTIMAL
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix[0].length==0)
{
return false;
}
int shortest = Math.min(matrix[0].length, matrix.length);
for(int i=0;i<shortest;i++)
{
boolean verticalfound = binarySearch(matrix, target, i, true);
boolean horizontalfound = binarySearch(matrix, target, i, false);
if(verticalfound||horizontalfound)
{
return true;
}
}
return false;
}
public static boolean binarySearch(int [][]matrix, int target, int start, boolean vertical)
{
int low = start;
int high =0;
if(vertical)
{
high = matrix[0].length-1;
}
else
{
high = matrix.length-1;
}
while(low <= high)
{
int mid = (low+high)/2;
if(vertical)
{
System.out.println("VERTICAL"+matrix[start][mid]);
//search vertical
if(matrix[start][mid]<target)
{
low = mid+1;
}
else if(matrix[start][mid]>target)
{
high = mid-1;
}
else
{
return true;
}
}
else
{
System.out.println("HORIZONTAL"+matrix[mid][start]);
//search horizontal
if(matrix[mid][start]<target)
{
low = mid+1;
}
else if(matrix[mid][start]>target)
{
high = mid-1;
}
else
{
return true;
}
}
}
return false;
}
}