1351. 统计有序矩阵中的负数
- 题号:力扣1351
- 知识点:矩阵
- 目标完成度:13/150
- 总结
题干:
思路:
- 1.两层循环暴力破解,注意每一行查找时,找到第一个负数则说明后面的都是负数
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
counter = 0
m = len(grid[0])
for w in grid:
for i, x in enumerate(w):
# i后面的全都是零
if x<0:
counter += (m - i)
break
return counter
- 2.任何
N^2
时间复杂度都可以优化为n*logn
。修改内层遍历,使用二分查找找出正负分解位置
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
counter = 0
m = len(grid[0])
for w in grid:
l, r = 0, m-1
if w[l]<0:
counter += m
elif w[r]>0:
continue
else:
# 二分查找
while (l+1 < r):
mid = l + (r-l) // 2
if w[mid] < 0:
r = mid
else:
l = mid
if w[l+1] < 0:
counter +=(m-l-1)
return counter
- 3.题解中发现的令人震惊的解法:转为字符串,查找
-
字符
class Solution:
def countNegatives(self, grid:List[List[int]]) -> int
return str(grid).count('-')