File tree 1 file changed +43
-3
lines changed
1 file changed +43
-3
lines changed Original file line number Diff line number Diff line change 1
- package kotlin
2
-
1
+ // binary search on rows to find row, then binary search on actual row O(log(m*n))
3
2
class Solution {
4
-
5
3
// TC: O(log m + log n)
6
4
fun searchMatrix (matrix : Array <IntArray >, target : Int ): Boolean {
7
5
var row = matrix.size
@@ -39,3 +37,45 @@ class Solution {
39
37
return false
40
38
}
41
39
}
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
+ }
You can’t perform that action at this time.
0 commit comments