Skip to content

Instantly share code, notes, and snippets.

@munguial
Created April 22, 2020 05:17
Show Gist options
  • Save munguial/a95836b1cc33aa5416cc591a1c6a66fc to your computer and use it in GitHub Desktop.
Save munguial/a95836b1cc33aa5416cc591a1c6a66fc to your computer and use it in GitHub Desktop.
Day 21 - Leftmost column with at least a one
// https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/530/week-3/3306/
class Solution {
fun leftMostColumnWithOne(binaryMatrix:BinaryMatrix):Int {
var result = 100
for (row in 0 until binaryMatrix.dimensions()[0]) {
result = minOf(result, bs(binaryMatrix, row))
}
return if (result == 100) -1 else result
}
fun bs(matrix: BinaryMatrix, row: Int): Int {
var a = 0
var b = matrix.dimensions()[1] - 1
while (a < b) {
val m = ((a + b) / 2).toInt()
val currVal = matrix.get(row, m)
if (currVal == 0) {
a = m + 1
} else {
b = m - 1
}
}
val minimum = minOf(a, b)
if (minimum >= 0 && matrix.get(row, minimum) == 1) {
return minimum
} else if (minimum + 1 < matrix.dimensions()[1]
&& matrix.get(row, minimum + 1) == 1) {
return minimum + 1
} else {
return 100
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment