Leftmost Column with at Least a One
Description
null
Solution(javascript)
/**
* // This is the BinaryMatrix's API interface.
* // You should not implement it, or speculate about its implementation
* function BinaryMatrix() {
* @param {integer} row, col
* @return {integer}
* this.get = function(row, col) {
* ...
* };
*
* @return {[integer, integer]}
* this.dimensions = function() {
* ...
* };
* };
*/
/**
* @param {BinaryMatrix} binaryMatrix
* @return {number}
*/
var leftMostColumnWithOne = function(binaryMatrix) {
const [rows, columns] = binaryMatrix.dimensions()
const getIndex = (row) => {
let result = -1
let left = 0
let right = columns - 1
while(left <= right) {
const middle = Math.floor(left + (right - left) / 2)
const value = binaryMatrix.get(row, middle)
if(value < 1) {
left = middle + 1
} else {
right = middle - 1
result = middle
}
}
return result
}
let result = -1
for(let row = 0; row < rows; row ++) {
const index = getIndex(row)
if(index !== -1) {
if(result !== -1) {
result = Math.min(index, result)
} else {
result = index
}
}
}
return result
};