classSolution(object): defcountNegatives(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) cnt = 0 for i inrange(m): for j inrange(n): if grid[i][j] < 0: cnt += 1 return cnt
一行解
1 2 3 4 5 6 7
classSolution(object): defcountNegatives(self, grid): """ :type grid: List[List[int]] :rtype: int """ returnsum([c<0for arr in grid for c in arr])
classSolution(object): defcountNegatives(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0])
defsearch(arr): deftest(m): return arr[m] > -1 l, r = 0, n while l<r: m = (l+r) // 2 if test(m-1) andnot test(m): return n-m ifnot test(m): r = m else: l = m+1 return n-l
cnt = 0 for i inrange(m): cnt += search(grid[i]) return cnt
一行解,同理但使用 bisect 函式
程式
1 2 3 4 5 6 7
classSolution(object): defcountNegatives(self, grid): """ :type grid: List[List[int]] :rtype: int """ returnsum([bisect.bisect_right(c[::-1], -1) for c in grid])
Complexity
Time Complexity: O(m* log n)
m 排操作 log n 次
Space Complexity: O(1)
基本上無使用到額外空間
觀查
思路
透過非只有 row 有非遞減特性、col 也有,來進行 traverse
程式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defcountNegatives(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0])
col = m cnt = 0
for row in grid: while0 < col and row[col-1] < 0: col -= 1 cnt += m-col return cnt
Complexity
Time Complexity: O(m+n)
有 m 排但全部排數的操作總共不超過 n 次,故為 m+n