forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchTwoDMatrix.java
More file actions
55 lines (53 loc) · 1.52 KB
/
SearchTwoDMatrix.java
File metadata and controls
55 lines (53 loc) · 1.52 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
public class Solution {
//binary search O(log(M*N))
public boolean searchMatrix(int[][] matrix, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int m = matrix.length;
int n = matrix[0].length;
int max = m * n - 1;
int min = 0;
while(max >= min){
int mid = (max + min) / 2;
int i = mid / n;
int j = mid % n;
if(matrix[i][j] == target)
return true;
else if(matrix[i][j] < target)
min = mid + 1;
else
max = mid - 1;
}
return false;
}
//O(M+N)
public boolean searchMatrix(int[][] matrix, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int m = matrix.length, n = matrix[0].length;
int i = 0, j = n - 1;
while(i < m && j >= 0){
if(matrix[i][j] > target){
--j;
}
else if(matrix[i][j] < target){
++i;
}
else
return true;
}
return false;
}
//O(M*N)
public boolean naiveSearch(int[][] matrix, int target){
int m = matrix.length;
int n = matrix[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == target)
return true;
}
}
return false;
}
}