1865.找出和为指定值得下标对

为了找出满足指定值得下标对,可以假设nums1[i]的值为num,从而tot-num就是要从nums2中找的的,可以事先维护一个哈希表,从而直接获取tot-num的出现次数。

class FindSumPairs {
    int[] nums1;
    int[] nums2;
    // nums2的长度很长
    Map<Integer, Integer> freq; // 用于统计nums2中各数字出现的频率
    public FindSumPairs(int[] nums1, int[] nums2) {
        // 初始化对象
        this.nums1 = nums1;
        this.nums2 = nums2;
        this.freq = new HashMap<>();
        // 初始化
        for (int num : nums2){
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }
    }
    
    public void add(int index, int val) {
        // 将val加到nums2[index]的值上
        // 可以直接按照索引进行操作,
        // 但是维护了频率表,因此需要先对频率表进行更新
        int oldValue = nums2[index];
        // 减少oldValue的频率
        freq.put(oldValue, freq.get(oldValue) - 1);
        // 如果减到0,则去掉
        if (freq.get(oldValue) == 0){
            freq.remove(oldValue);
        }

        // 更新
        nums2[index] += val;
        // 更新freq
        int newValue = nums2[index];
        freq.put(newValue, freq.getOrDefault(newValue, 0)+1);
    }
    
    public int count(int tot) {
        // 返回满足条件的nums1[i]+nums2[j]=tot下标对数量
        // 注意时间复杂度
        // 利用freq进行统计
        int res = 0;
        for (int num : nums1){
            // 余数
            int complement = tot - num;
            res += freq.getOrDefault(complement, 0);
        }
        return res;
    }
}

/**
 * Your FindSumPairs object will be instantiated and called as such:
 * FindSumPairs obj = new FindSumPairs(nums1, nums2);
 * obj.add(index,val);
 * int param_2 = obj.count(tot);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

所谓远行Misnearch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值