https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/description/
这道题就是2分横轴,再2分纵轴。横轴的时候,传入X进行2分,X那行一定不是全0,然后找到最左边含1的边界。再找最右边含1的边界。
在找左边界时,我们取完中点后如果发现,全0 的话,说明含1边界再中点右侧,反之在左侧。
找右边界时,反一反。
纵轴也是这个思想。
int h;
int l;
public int minArea(char[][] recs, int y, int x) {
h = recs.length;
l = recs[0].length;
int[] hor = help(recs,x,true);
int[] ver = help(recs,y,false);
return (hor[1]-hor[0]+1)*(ver[1]-ver[0]+1);
}
private int[] help(char[][] recs, int b,boolean isH) {
int s = 0, e = b;
int[] res = new int[2];
while(s<=e){
int m = (e-s)/2+s;
if(allZero(m,recs,isH)){
s = m+1;
}else{
e = m-1;
}
}
res[0] = e+1;
s = b;
e = (isH?l:h)-1;
while(s<=e){
int m = (e-s)/2+s;
if(allZero(m,recs,isH)){
e = m-1;
}else{
s = m+1;
}
}
res[1] = s-1;
return res;
}
private boolean allZero(int m, char[][] recs, boolean isH) {
if(isH){
for(int i = 0;i < h;i++)
if(recs[i][m] != '0') return false;
}
else{
for(int j = 0;j < l;j++)
if(recs[m][j] != '0') return false;
}
return true;
}