0%

Leftmost Column with at Least a One

Question

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

Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn’t 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 a list of 2 elements [rows, cols], which means the matrix is rows * 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 you’re given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.

Solution

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
/*
@param: BinaryMatrix
@return: int
Algorithm: 题目有点花哨,就是一个多个排好序的行里,查找每一行第一次'1'出现的位置,去这些值得最小值
Binary Search.
*/
public int leftMostColumnWithOne(BinaryMatrix b) {
int row = b.dimensions().get(0);
int col = b.dimensions().get(1);

int ret = col;
for (int i = 0; i < row; i++) {
if (b.get(i, 0) == 1) return 0;
else if (b.get(i, col-1) == 0) continue;
ret = Math.min(ret, help(i, col, b));
}
return ret == col ? -1 : ret;
}

private int help(int row, int col, BinaryMatrix b) {
int i = 0, j = col-1;
while (i < j) {
int mid = (i+j)/2;
if (b.get(row, mid) == 1) j = mid;
else i = mid+1;
}
return j;
}