1428. Leftmost Column with at Least a One

ss
2 min readFeb 13, 2021

--

這是一題二分搜尋法的變化題, 主要就是要把col當作二分搜尋法, 當發現有一我們就把r = mid- 1, 當沒有1就是 l = mid + 1, 直到 l > r

算是蠻新穎的題目, 可以try看看, 最後面需要檢查l 是否已經大於col數

/**
* // 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 {
public:
bool checkcol(BinaryMatrix &b, int col){
auto dims = b.dimensions();
int rows = dims[0];
for(int i = 0; i < rows;i++){

if(b.get(i, col) == 1){
return true;
}
}
return false;
}
int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) {
auto dims = binaryMatrix.dimensions();
int rows = dims[0];
int cols = dims[1];
int l = 0;
int r = cols -1;
while(l <= r){
int mid = (l + r) /2;
if(checkcol(binaryMatrix, mid)){
r = mid - 1;
}else{
l = mid + 1;
}
}
if( l < cols && checkcol(binaryMatrix, l)){
return l;
}
return -1;
}
};

--

--

ss
ss

No responses yet