-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday15.java
More file actions
41 lines (39 loc) · 1.1 KB
/
day15.java
File metadata and controls
41 lines (39 loc) · 1.1 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
//Problem:Search a 2D matrix 2
//https://leetcode.com/problems/search-a-2d-matrix-ii/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row=0,col=matrix[0].length-1;
while(row<matrix.length && col>=0){
if(matrix[row][col]==target)
return true;
else if(matrix[row][col]>target)
col--;
else
row++;
}
return false;
}
}
//TC:O(m+n)
//Problem:Search a 2D matrix
//https://leetcode.com/problems/search-a-2d-matrix/description/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
int start = 0;
int end = row * col - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (matrix[mid / col][mid % col] == target)
return true;
else if (matrix[mid / col][mid % col] < target)
start = mid + 1;
else
end = mid - 1;
}
return false;
}
}
//TC:O(logmn)
//SC:O(1)