(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);
 */
相关推荐
Java成神之路-1 分钟前
面试题:Spring AOP底层实现原理
java·spring aop
Python私教4 分钟前
如意Agent日志系统重构:从 print() 大海捞针到结构化可观测性栈
java·前端·重构
迷途之人不知返6 分钟前
优先级队列:priority_queue
数据结构·c++
jieyucx9 分钟前
Go 零基础数据结构:顺序表(像「排抽屉」一样学增删改查)
java·数据结构·golang
曦夜日长10 分钟前
C++ STL容器string(一):string的变量细节、默认函数的认识以及常用接口的使用
java·开发语言·c++
代码中介商12 分钟前
C++ STL 标准模板库完全指南:从容器到迭代器
开发语言·c++·stl
winner888114 分钟前
C++ 构造函数、析构函数、虚函数、虚析构
开发语言·c++
想唱rap15 分钟前
应用层协议与序列化
linux·运维·服务器·网络·数据结构·c++·算法
北山有鸟17 分钟前
IS_ERR 判断出错后,再用 PTR_ERR 把它强制转换回 int 型的错误码作为函数的返回值。
java·开发语言
许长安18 分钟前
protobuf 使用详解
c++·经验分享·笔记·中间件