## LeetCode-Python-1351. 统计有序矩阵中的负数 (数组 + 二分）

m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100

``````class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])

res = 0
for i in range(m):
for j in range(n):
if grid[i][j] < 0:
res += 1
return res``````

``````class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])

res = 0
for i in range(m):
if grid[i][0] < 0:
break
for j in range(n):
if grid[i][j] < 0:
break
res += 1

return m*n - res``````

``````class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])

def findFirstNegativeElementIndex(l):
left, right = 0, len(l) - 1
while left <= right:
mid = (left + right) // 2

if l[mid] >= 0:
left = mid + 1
else:
right = mid - 1
return left

res = 0
for i in range(m):
cnt = findFirstNegativeElementIndex(grid[i])
res += cnt

return m*n - res``````