-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0074-search-a-2d-matrix.kt
81 lines (71 loc) · 1.96 KB
/
0074-search-a-2d-matrix.kt
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// binary search on rows to find row, then binary search on actual row O(log(m*n))
class Solution {
// TC: O(log m + log n)
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
var row = matrix.size
var col = matrix.first().size
var top = 0
var bot = row - 1
while ( top <= bot ){
row = (top + bot ) / 2
if(target > matrix[row][col - 1]){
top = row + 1
} else if(target < matrix[row][0]) {
bot = row - 1
} else {
break
}
}
if((top > bot)) return false
row = (top + bot) / 2
var l = 0
var r = col - 1
while(l <= r){
var m = (l + r) / 2
if(target > matrix[row][m]){
l = m + 1
} else if(target < matrix[row][m]){
r = m - 1
} else {
return true
}
}
return false
}
}
//binary search on whole matrix (search the matrix as an sorted array) O(log(m*n))
class Solution {
fun searchMatrix(mt: Array<IntArray>, t: Int): Boolean {
val rows = mt.size
val cols = mt[0].size
var l = 0
var r = rows * cols - 1
while (l != r) {
val m = (l + r) / 2
if (mt[m / cols][m % cols] < t)
l = m + 1
else
r = m
}
return mt[r / cols][r % cols] == t
}
}
//treat the matrix as an BST, root at mt[0][-1] O(m + n)
class Solution {
fun searchMatrix(mt: Array<IntArray>, t: Int): Boolean {
val rows = mt.size
val cols = mt[0].size
var row = 0
var col = cols - 1
while (row < rows && col >= 0) {
val cur = mt[row][col]
if (cur > t)
col--
else if (cur < t)
row++
else
return true
}
return false
}
}