Given a
m x n
matrixgrid
which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers ingrid
.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
Follow up: Could you find an
O(n + m)
solution?
給予一個
m x n
並且欄與列都以非遞增順序排序的矩陣grid
,回傳grid
中非負數的數量。
限制:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
進階題:你可以找到一個
O(n + m)
的解法嗎?
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
O(m * n)
j
其實不需要重置n + m
,達到 O(n + m)
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int count = 0;
for(int i = 0; i < grid.size(); i++)
for(int j = grid[i].size() - 1; j >= 0; j--)
count += grid[i][j] < 0;
return count;
}
};
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int count = 0;
int j = 0;
int n = grid[0].size();
for(int i = 0; i < grid.size(); i++)
{
while(j != n && grid[i][n - j - 1] < 0)
{
j++;
}
count += j;
}
return count;
}
};
LeetCode
C++