(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);
 */
相关推荐
fqbqrr5 小时前
2601C++,cmake与导入
c++
fqbqrr6 小时前
2601C++,编写自己模块
c++
wearegogog1236 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
韩师学子--小倪6 小时前
fastjson与gson的toString差异
java·json
一只小小汤圆6 小时前
几何算法库
算法
Drawing stars6 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
Evand J6 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
nbsaas-boot6 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
行百里er7 小时前
用 ThreadLocal + Deque 打造一个“线程专属的调用栈” —— Spring Insight 的上下文管理术
java·后端·架构
leo__5207 小时前
基于MATLAB的交互式多模型跟踪算法(IMM)实现
人工智能·算法·matlab