LeetCode_1351_统计有序矩阵中的负数

题目链接

解题思路

  • 暴力法
  • 二分查找法
  • 通过二分查找可以找到每一行中从前往后的第一个负数,那么这个位置之后导这一行的末尾里所有的数必然是负数,可以直接统计
    • 遍历矩阵的每一行
    • 二分查找到改行从前往后的第一个负数,考虑第i行,我们记这个位置为 p o s i pos_i posi,那么第i行[ p o s i , m − 1 pos_i,m - 1 posi,m1]中的所有数都是负数,所以这一行对答案的贡献就是m - 1 - p o s i pos_i posi + 1 = m - p o s i pos_i posi
    • 最后的答案就是 ∑ i = 0 n − 1 ( m − p o s i ) \sum_{i = 0}^{n-1}{(m-pos_i)} i=0n1(mposi)

AC代码

//暴力法
class Solution {
    public int countNegatives(int[][] grid) {
        int ans = 0;
        for (int[] value : grid) {
            for (int j = 0; j < grid[0].length; j++) {
                if (value[j] < 0)
                    ans++;
            }
        }
        return ans;
    }
}
//二分查找
class Solution {
public:
    int countNegatives(vector<vector<int>>& grid) {
        int num=0;
        for (auto x:grid){
            int l=0,r=(int)x.size()-1,pos=-1;
            while (l<=r){
                int mid=l+((r-l)>>1);
                if (x[mid]<0){
                    pos=mid;
                    r=mid-1;
                }
                else l=mid+1;
            }
            if (~pos) num+=(int)x.size()-pos;// pos=-1表示这一行全是>=0的数,不能统计
        }
        return num;
    }
};

本地测试代码

package com.company;

public class Solution_1351 {
    public static int countNegatives(int[][] grid) {
        int ans = 0;
        for (int[] value : grid) {
            for (int j = 0; j < grid[0].length; j++) {
                if (value[j] < 0)
                    ans++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(countNegatives(new int[][]{{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}}));
        System.out.println(countNegatives(new int[][]{{3, 2}, {1, 0}}));
        System.out.println(countNegatives(new int[][]{{1, -1}, {-1, -1}}));
        System.out.println(countNegatives(new int[][]{{-1}}));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值