1 import bisect 2 class Solution: 3 def countNegatives(self, grid: 'List[List[int]]') -> int: 4 m = len(grid) 5 n = len(grid[0]) 6 sums = 0 7 for i in range(m): 8 aryi = grid[i][::-1] 9 index = bisect.bisect_right(aryi,-1) 10 if index == n: 11 sums += (m - i) * n 12 break 13 sums += index 14 return sums
使用二分查找加速,时间复杂度O(m * logn)。