1351. Count Negative Numbers in a Sorted Matrix*

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值