给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。 请你统计并返回 grid 中 负数 的数目。
示例 1:
输入:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
输出:8
解释:矩阵中共有 8 个负数。
示例 2:
输入:grid = [[3,2],[1,0]]
输出:0
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
方法一:(暴力法)
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
count = 0
for num in grid:
for g in num:
if g < 0:
count += 1
return count
方法二:(二分法)
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
total = 0
left, right = 0, len(grid[0]) - 1
n = len(grid)
while left < n and right >= 0:
if grid[left][right] >= 0:
left += 1
else:
total += n - left
right -= 1
return total