1351. 统计有序矩阵中的负数
方法一:二分查找。
class Solution(object):
# 二分法
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ans = 0
for nums in grid:
if nums[0] < 0:
ans += len(nums)
continue
if nums[-1] >= 0:
continue
i, j = 0, len(nums) - 1
while i <= j:
mid = int(i + (j - i) / 2)
if nums[mid] >= 0:
i = mid + 1
else:
j = mid - 1
if nums[i] < 0:
ans += len(nums) - i
return ans
方法二:暴力解。
class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ans = 0
for i in range(len(grid)):
if grid[i][0] < 0:
ans += len(grid[i])
else:
for j in range(len(grid[i])):
if grid[i][j] < 0:
ans += 1
return ans