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