[leetcode] 1351. Count Negative Numbers in a Sorted Matrix

网友投稿 286 2022-08-25

[leetcode] 1351. Count Negative Numbers in a Sorted Matrix

Description

Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.

Return the number of negative numbers in grid.

Example 1:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]Output: 8Explanation: There are 8 negatives number in the matrix.

Example 2:

Input: grid = [[3,2],[1,0]]Output: 0

Example 3:

Input: grid = [[1,-1],[-1,-1]]Output: 3

Example 4:

Input: grid = [[-1]]Output: 1

Constraints:

m == grid.lengthn == grid[i].length1 <= m, n <= 100-100 <= grid[i][j] <= 100

分析

题目的意思是:统计一个矩阵里面所有负数的个数,因为矩阵已经是有序了,负数集中在右方和下方,所以遍历的时候倒序遍历。

代码

class Solution: def countNegatives(self, grid: List[List[int]]) -> int: m=len(grid) n=len(grid[0]) res=0 for i in range(m-1,-1,-1): for j in range(n-1,-1,-1): if(grid[i][j]<0): res+=1 else: break return res

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1222. Queens That Can Attack the King
下一篇:红酒代理加盟商如何做好营销?营销战也是心理战!(红酒营销渠道)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~