[LeetCode] Leftmost Column with at Least a One

1428. Leftmost Column with at Least a One

(This problem is an interactive problem.)

A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.

Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.

You can’t access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:

  • BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).
  • BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.

Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.

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
/**
* // This is the BinaryMatrix's API interface.
* // You should not implement it, or speculate about its implementation
* class BinaryMatrix {
* public:
* int get(int row, int col);
* vector<int> dimensions();
* };
*/
class Solution {
int binarySearch(BinaryMatrix& b, int l, int r, int ans, int row) {
int res = INT_MAX;
do {
int m = (l + r) / 2, n = b.get(row, m);
if(!n && m >= ans) return INT_MAX;
if(n) res = min(res, r = m);
else l = m;
} while(l + 1 < r);
return res;
}
public:
int leftMostColumnWithOne(BinaryMatrix &b) {
vector<int> rowAndCol = b.dimensions();
int r = rowAndCol[0], c = rowAndCol[1], res = INT_MAX;
for(int i = 0; i < r; i++, c = min(c, res)) {
if(b.get(i, 0)) return 0;
if(!b.get(i, c - 1)) continue;
res = min(res, binarySearch(b, 0, c, res, i));
}
return res == INT_MAX ? - 1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/06/PS/LeetCode/leftmost-column-with-at-least-a-one/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.