LeetCode 1351. Count Negative Numbers in a Sorted Matrix
Question
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]] |
Solution
You can solve it by brute force. But you also can traversal from the top-right position, when it is smaller than 0, we can add one columum in one time and move. Otherwise, we go to the next row.
Code
1 | // time:O(m + n) space:O(1) |