Skip to content

Add 74_Search_A_2D_Matrix.kt #767

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 9, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions kotlin/74-Search-A-2D-Matrix.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
}
}