二分查找到改行从前往后的第一个负数,考虑第i行,我们记这个位置为
p
o
s
i
pos_i
posi,那么第i行[
p
o
s
i
,
m
−
1
pos_i,m - 1
posi,m−1]中的所有数都是负数,所以这一行对答案的贡献就是m - 1 -
p
o
s
i
pos_i
posi + 1 = m -
p
o
s
i
pos_i
posi
最后的答案就是
∑
i
=
0
n
−
1
(
m
−
p
o
s
i
)
\sum_{i = 0}^{n-1}{(m-pos_i)}
∑i=0n−1(m−posi)
AC代码
//暴力法classSolution{publicintcountNegatives(int[][] grid){int ans =0;for(int[] value : grid){for(int j =0; j < grid[0].length; j++){if(value[j]<0)
ans++;}}return ans;}}