(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);
 */
相关推荐
only-qi1 天前
146. LRU 缓存
java·算法·缓存
xuxie131 天前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王1 天前
Java中的多态有什么用?
java·后端
梁辰兴1 天前
数据结构:排序
数据结构·算法·排序算法·c·插入排序·排序·交换排序
Murphy_lx1 天前
Lambda表达式
开发语言·c++
666和7771 天前
Struts2 工作总结
java·数据库
中草药z1 天前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
yangpipi-1 天前
C++并发编程-23. 线程间切分任务的方法
开发语言·c++
Lris-KK1 天前
【Leetcode】高频SQL基础题--1731.每位经理的下属员工数量
sql·leetcode
野犬寒鸦1 天前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试