forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
74-Search-A-2D-Matrix.kt
41 lines (35 loc) · 945 Bytes
/
74-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
package kotlin
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
}
}