Given a m x 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

这题不难,但是要找到O(M+N),得利用题目中给的特性。我们这里直接暴力算了。

class CountNegativeNumbersInASortedMatrix : public Solution {
public:
    void Exec() {

    }
    int countNegatives(vector<vector<int>>& grid) {
        int count = 0;
        for (auto &row : grid) {
            for (int i = 0; i < row.size(); i++) {
                if (row[i] < 0) {
                    count += row.size() - i;
                    break;
                }
            }
        }
        return count;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day