题意
给你两个整数数组 nums1 和 nums2 ,请你实现一个支持下述两类查询的数据结构:
1.累加 ,将一个正整数加到 nums2 中指定下标对应元素上。
2.计数 ,统计满足 nums1[i] + nums2[j] 等于指定值的下标对 (i, j) 数目(0 <= i < nums1.length 且 0 <= j < nums2.length)。
分析
1.累加是仅将nums2中的元素进行操作,因此nums2的所有元素都必须要动态更新。
2.计数这个步骤就非常像两数之和了。
代码
class FindSumPairs {
public:
vector<int> a, b;//将输入数组nums1和nums2变为全局数组
//创建一个哈希表用来存储数组num2的所有元素,key为数值,value为数值的出现次数;为什么是num2而不是nums1呢?
unordered_map<int, int> h;
FindSumPairs(vector<int>& nums1, vector<int>& nums2) {
a = nums1, b = nums2;
for (auto& t : nums2) h[t]++;//将nums2的所有元素存入哈希表中
}
void add(int index, int val) {
h[b[index]]--;//将下标为index的值移除哈希表
b[index] += val;//将下标为index的值加上val
h[b[index]]++; //再将下标为index的值存入哈希表中
}
int count(int tot) {
int ans = 0;
for (auto& t :a) {
ans += h[tot - t];//统计有多少下标对满足条件
}
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);
*/