1351. Count Negative Numbers in a Sorted Matrix
Problem:
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: 8
Explanation: 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.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
思路:
当找到一个负数时,这个负数的右方和下方均为负数,则可以不用再查找。保存一个变量col
为查找到每行第一个负数所在的列,这意味着下次查找的时候只需查找到col-1
列,当col
为0时,说明接下来的行全为负数,则可不需查找。
Solution (C++):
int countNegatives(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int col = n, count = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < col; ++j) {
if (grid[i][j] < 0) {
count += (col-j) * (m-i);
col = j;
break;
}
if (col == 0) break;
}
}
return count;
}
性能:
Runtime: 16 ms Memory Usage: 8 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。