为了找出满足指定值得下标对,可以假设nums1[i]的值为num,从而tot-num就是要从nums2中找的的,可以事先维护一个哈希表,从而直接获取tot-num的出现次数。
class FindSumPairs {
int[] nums1;
int[] nums2;
// nums2的长度很长
Map<Integer, Integer> freq; // 用于统计nums2中各数字出现的频率
public FindSumPairs(int[] nums1, int[] nums2) {
// 初始化对象
this.nums1 = nums1;
this.nums2 = nums2;
this.freq = new HashMap<>();
// 初始化
for (int num : nums2){
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
}
public void add(int index, int val) {
// 将val加到nums2[index]的值上
// 可以直接按照索引进行操作,
// 但是维护了频率表,因此需要先对频率表进行更新
int oldValue = nums2[index];
// 减少oldValue的频率
freq.put(oldValue, freq.get(oldValue) - 1);
// 如果减到0,则去掉
if (freq.get(oldValue) == 0){
freq.remove(oldValue);
}
// 更新
nums2[index] += val;
// 更新freq
int newValue = nums2[index];
freq.put(newValue, freq.getOrDefault(newValue, 0)+1);
}
public int count(int tot) {
// 返回满足条件的nums1[i]+nums2[j]=tot下标对数量
// 注意时间复杂度
// 利用freq进行统计
int res = 0;
for (int num : nums1){
// 余数
int complement = tot - num;
res += freq.getOrDefault(complement, 0);
}
return res;
}
}
/**
* 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);
*/
5万+

被折叠的 条评论
为什么被折叠?



