-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ74Search2DMatrix.java
More file actions
48 lines (39 loc) · 1.31 KB
/
Q74Search2DMatrix.java
File metadata and controls
48 lines (39 loc) · 1.31 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
/*
@b-knd (jingru) on 23 July 2022 10:28:00
*/
import java.util.*;
class Q74Search2DMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int row = -1;
//search target row by comparing last elements of row
for(int i = 0; i < matrix.length; i++){
int element = matrix[i][matrix[0].length-1];
if(element == target){
return true;
} else if(element > target){
row = i;
break;
}
}
//row not found
if(row == -1){
return false;
}
//binary search, refer Q704 (or can use Arrays.binarySearch(array, target))
int start = 0;
int end = matrix[0].length-1;
while(start <= end){
int midpoint = (start + end)/2;
if(matrix[row][midpoint] == target){
return true;
} else if(matrix[row][midpoint] < target){
start = midpoint + 1;
} else{
end = midpoint - 1;
}
}
return false;
}
}
//Runtime: 0 ms, faster than 100.00% of Java online submissions for Search a 2D Matrix.
//Memory Usage: 41.9 MB, less than 92.96% of Java online submissions for Search a 2D Matrix.