(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)

题目:1865. 找出和为指定值的下标对


思路:哈希表,时间复杂度0(n)。
记录nums1、nums2数组,同时使用哈希表mp来维护数组nums2里元素出现的情况。

C++版本:

cpp 复制代码
class FindSumPairs {
public:
    vector<int> a1,a2; 
    unordered_map<int,int> mp;
    FindSumPairs(vector<int>& nums1, vector<int>& nums2) {
        a1=nums1;
        a2=nums2;
        for(auto x:nums2){
            mp[x]++;
        }
    }
    
    void add(int index, int val) {
        int x=a2[index];
        mp[x]--;
        a2[index]+=val;
        mp[x+val]++;
    }
    
    int count(int tot) {
        int ans=0;
        for(auto x:a1){
            ans+=mp[tot-x];
        }
        return ans;
    }
};

/**
 * 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);
 */

JAVA版本:

java 复制代码
class FindSumPairs {
    int[] a1,a2;
    Map<Integer,Integer> mp=new HashMap<>();

    public FindSumPairs(int[] nums1, int[] nums2) {
        a1=nums1;
        a2=nums2;
        for(var x:a2){
            mp.merge(x,1,Integer::sum);
        }    
    }
    
    public void add(int index, int val) {
        int x=a2[index];
        mp.merge(x,-1,Integer::sum);
        a2[index]+=val;
        mp.merge(x+val,1,Integer::sum);
    }
    
    public int count(int tot) {
        int ans=0;
        for(var x:a1){
            ans+=mp.getOrDefault(tot-x,0);
        }
        return ans;
    }
}

/**
 * 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);
 */

GO版本:

go 复制代码
type FindSumPairs struct {
    a1 []int
    a2 []int
    mp map[int]int
}


func Constructor(nums1 []int, nums2 []int) FindSumPairs {
    mp:=map[int]int{}
    for _,x:=range nums2 {
        mp[x]++
    }
    return FindSumPairs{
        a1:nums1,
        a2:nums2,
        mp:mp,
    }
}


func (this *FindSumPairs) Add(index int, val int)  {
    x:=this.a2[index]
    this.mp[x]--
    this.a2[index]+=val
    this.mp[x+val]++
}


func (this *FindSumPairs) Count(tot int) int {
    ans:=0
    for _,x:=range this.a1 {
        ans+=this.mp[tot-x]
    }
    return ans
}


/**
 * Your FindSumPairs object will be instantiated and called as such:
 * obj := Constructor(nums1, nums2);
 * obj.Add(index,val);
 * param_2 := obj.Count(tot);
 */
相关推荐
2401_837088506 分钟前
简要总结 HashSet 和 HashMap(Java)
java·开发语言
毕设源码-钟学长25 分钟前
【开题答辩全过程】以 基于Java的家政服务管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
小白学大数据28 分钟前
Java 爬虫对百科词条分类信息的抓取与处理
java·开发语言·爬虫
Gold_Dino36 分钟前
agc011_e 题解
算法
zmzb01031 小时前
C++课后习题训练记录Day56
开发语言·c++
编程小Y1 小时前
C++ Insights
开发语言·c++
bubiyoushang8881 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab
风筝在晴天搁浅1 小时前
hot100 240.搜索二维矩阵Ⅱ
算法·矩阵
girl-07261 小时前
2025.12.24代码分析
算法
Coder_Boy_1 小时前
Spring 核心思想与企业级最佳特性(实践级)事务相关
java·数据库·spring