Skip to content

Commit 2446cdd

Browse files
authored
Update 0074-search-a-2d-matrix.kt
1 parent a3d9b42 commit 2446cdd

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

kotlin/0074-search-a-2d-matrix.kt

+43-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
package kotlin
2-
1+
// binary search on rows to find row, then binary search on actual row O(log(m*n))
32
class Solution {
4-
53
// TC: O(log m + log n)
64
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
75
var row = matrix.size
@@ -39,3 +37,45 @@ class Solution {
3937
return false
4038
}
4139
}
40+
41+
//binary search on whole matrix (search the matrix as an sorted array) O(log(m*n))
42+
class Solution {
43+
fun searchMatrix(mt: Array<IntArray>, t: Int): Boolean {
44+
val rows = mt.size
45+
val cols = mt[0].size
46+
47+
var l = 0
48+
var r = rows * cols - 1
49+
while (l != r) {
50+
val m = (l + r) / 2
51+
if (mt[m / cols][m % cols] < t)
52+
l = m + 1
53+
else
54+
r = m
55+
}
56+
57+
return mt[r / cols][r % cols] == t
58+
}
59+
}
60+
61+
//treat the matrix as an BST, root at mt[0][-1] O(m + n)
62+
class Solution {
63+
fun searchMatrix(mt: Array<IntArray>, t: Int): Boolean {
64+
val rows = mt.size
65+
val cols = mt[0].size
66+
67+
var row = 0
68+
var col = cols - 1
69+
while (row < rows && col >= 0) {
70+
val cur = mt[row][col]
71+
if (cur > t)
72+
col--
73+
else if (cur < t)
74+
row++
75+
else
76+
return true
77+
}
78+
79+
return false
80+
}
81+
}

0 commit comments

Comments
 (0)