-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLc_74.java
More file actions
59 lines (47 loc) · 1.47 KB
/
Lc_74.java
File metadata and controls
59 lines (47 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
58
59
public class Lc_74 {
public static void main(String[] args) {
int [][] matrix = {
{1,3,5,7},
{10,11,16,20},
{23,30,34,60}
};
int target = 6;
System.out.println(searchMatrix(matrix, target));
}
static boolean searchMatrix(int[][] matrix, int target) {
int rStart = 0;
int rEnd = matrix.length-1;
int cStart = 0;
int cEnd = matrix[0].length-1;
while(rStart <= rEnd){
int rMid = rStart + ( rEnd - rStart ) / 2;
if(matrix[rMid][cStart] <= target && matrix[rMid][cEnd] >= target){
return binarySearch(matrix, target, rMid) ? true : false;
}
else if ( matrix[rMid][cStart] > target){
rEnd = rMid - 1;
}
else if ( matrix[rMid][cEnd] < target){
rStart = rMid + 1;
}
}
return false;
}
static boolean binarySearch(int[][] matrix, int target, int r){
int cStart = 0;
int cEnd = matrix[0].length - 1;
while (cStart <= cEnd){
int mid = cStart + (cEnd - cStart) / 2;
if (matrix[r][mid] == target){
return true;
}
else if (target < matrix[r][mid]){
cEnd = mid - 1;
}
else if (target > matrix[r][mid]){
cStart = mid + 1;
}
}
return false;
}
}