LeetCode #1351. Count Negative Numbers in a Sorted Matrix
题目
1351. Count Negative Numbers in a Sorted Matrix
解题方法
从矩阵的右下角开始遍历矩阵的对角线,以右下角的点为起始点(startrow, startcol),如果此点是正值就break掉循环,否则分别遍历这一行和这一列(跳过这个点),然后把startrow和startcol分别减1,直到其中一个为-1时结束循环。
时间复杂度:O(m*n)
空间复杂度:O(1)
代码
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
startrow, startcol = len(grid) - 1, len(grid[0]) - 1
negcount = 0
while startrow > -1 and startcol > -1:
if grid[startrow][startcol] < 0:
negcount += 1
else:
break
for i in range(startrow-1, -1, -1):
if grid[i][startcol] < 0:
negcount += 1
else:
break
for j in range(startcol-1, -1, -1):
if grid[startrow][j] < 0:
negcount += 1
else:
break
startrow -= 1
startcol -= 1
return negcount

浙公网安备 33010602011771号