-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain240.java
More file actions
59 lines (56 loc) · 1.56 KB
/
Main240.java
File metadata and controls
59 lines (56 loc) · 1.56 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
package HOT100;
/**
* 每行都进行二分搜索
*/
public class Main240 {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) {
return false;
}
for (int i = 0; i < matrix.length; i++) {
if(matrix[i][0] > target) {
break;
}
if(matrix[i][matrix[i].length - 1] < target) {
continue;
}
int col = binarySearch(matrix[i], target);
if(col != -1) {
return true;
}
}
return false;
}
private int binarySearch(int[] matrix, int target) {
int n = matrix.length, left = 0, right = n - 1;
for (int i = 0; i < n; i++) {
int mid = (left + right) / 2;
if (matrix[mid] == target) {
return mid;
} else if (matrix[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
class Main240_1 {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = 0, col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if(target > matrix[row][col]) {
row ++;
} else if (target < matrix[row][col]) {
col --;
} else {
return true;
}
}
return false;
}
}