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:
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
C++ 实现 1
骗人🤥, 根本不是二分法 🤣🤣🤣… 从矩阵左下角开始搜索, 如果 grid[r][c]
为负, 那么当前行 col >= c
的都是负数, 个数为 n - c
(其中 n
为矩阵的列数), 然后进入到上一行; 如果 grid[r][c]
为正, 那么继续向下一列搜索.
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), count = 0;
int r = m - 1, c = 0;
while (r >= 0 && c < n) {
if (grid[r][c] < 0) {
-- r;
count += n - c;
} else ++ c;
}
return count;
}
};