(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);
 */
相关推荐
缺点内向3 小时前
Java:创建、读取或更新 Excel 文档
java·excel
R-G-B4 小时前
【25】MFC入门到精通——MFC静态文本框 中字符串 连续输出 不覆盖先前的文本 换行输出
c++·mfc·mfc静态文本框输出字符串·mfc静态文本框连续输出字符串·mfc静态文本框换行输出字符串
我搞slam4 小时前
快乐数--leetcode
算法·leetcode·哈希算法
带刺的坐椅4 小时前
Solon v3.4.7, v3.5.6, v3.6.1 发布(国产优秀应用开发框架)
java·spring·solon
WWZZ20254 小时前
快速上手大模型:机器学习3(多元线性回归及梯度、向量化、正规方程)
人工智能·算法·机器学习·机器人·slam·具身感知
四谎真好看5 小时前
Java 黑马程序员学习笔记(进阶篇18)
java·笔记·学习·学习笔记
桦说编程5 小时前
深入解析CompletableFuture源码实现(2)———双源输入
java·后端·源码
东方佑5 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
java_t_t5 小时前
ZIP工具类
java·zip
西阳未落6 小时前
LeetCode——二分(进阶)
算法·leetcode·职场和发展