Leftmost Column with at Least a One
给一个2d数组, 里面全是1和0, 里面的row是按照升序排列的. 给一个api, 需要调这个api求最左边第一次出现1的列.
这个一看就是二叉.
/**
* // This is the BinaryMatrix's API interface.
* // You should not implement it, or speculate about its implementation
* interface BinaryMatrix {
* public int get(int row, int col) {}
* public List<Integer> dimensions {}
* };
*/
class Solution {
public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
int row = binaryMatrix.dimensions().get(0);
int col = binaryMatrix.dimensions().get(1);
int res = Integer.MAX_VALUE;
for(int i = 0; i < row; i++) {
res = Math.min(res, find(binaryMatrix, i, col));
}
return res == Integer.MAX_VALUE ? -1 : res;
}
private int find(BinaryMatrix binaryMatrix, int row, int col) {
int left = 0;
int right = col - 1;
int res = Integer.MAX_VALUE;
while(left <= right) {
int mid = left + (right - left) / 2;
if(binaryMatrix.get(row, mid) == 1){
right = mid - 1;
res = mid;
}
else
left = mid + 1;
}
return res;
}
}