题目地址:
https://leetcode.com/problems/leftmost-column-with-at-least-a-one/
给定一个 m × n m\times n m×n的 0 − 1 0-1 0−1矩阵,其每一行都是不减的。求其最左边的含 1 1 1的列的下标。
可以用二分。代码如下:
import java.util.List;
public class Solution {
public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
int col = binaryMatrix.dimensions().get(1);
int l = 0, r = col - 1;
while (l < r) {
int mid = l + (r - l >> 1);
if (check(mid, binaryMatrix)) {
r = mid;
} else {
l = mid + 1;
}
}
return check(l, binaryMatrix) ? l : -1;
}
private boolean check(int col, BinaryMatrix binaryMatrix) {
for (int i = 0; i < binaryMatrix.dimensions().get(0); i++) {
if (binaryMatrix.get(i, col) == 1) {
return true;
}
}
return false;
}
}
interface BinaryMatrix {
int get(int row, int col);
List<Integer> dimensions();
}
时间复杂度 O ( m log n ) O(m\log n) O(mlogn),空间 O ( 1 ) O(1) O(1)。