1351. Count Negative Numbers in a Sorted Matrix
https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/
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:
Example 2:
Example 3:
Example 4:
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
矩阵行和列已经都按照不递增的顺序排好,问矩阵中负数的个数。直观解法遍历每一行然后做个二分,不过由于它行和列都满足不递增,因此形成了类似这样的矩阵:
++++++ ++++-- ++++-- +++--- +----- +-----
所以可以从右上角开始向左遍历,如果遇到非负意味着前面都不可能是负数,调到下一行,同时继续保持当前遍历到的列依次接着遍历。
Previous1333. Filter Restaurants by Vegan-Friendly, Price and DistanceNextLeftmost Column with at Least a One
Last updated
Was this helpful?