[LeetCode] Finding Pairs With a Certain Sum

1865. Finding Pairs With a Certain Sum

You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types:

  1. Add a positive integer to an element of a given index in the array nums2.
  2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length).

Implement the FindSumPairs class:

  • FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2.
  • void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val.
  • int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class FindSumPairs {
unordered_map<int, long> n1;
unordered_map<int, long> n2;
vector<int> num2;
public:
FindSumPairs(vector<int>& nums1, vector<int>& nums2) : num2(nums2) {
for(auto& n : nums1) n1[n]++;
for(auto& n : nums2) n2[n]++;
}

void add(int index, int val) {
n2[num2[index]]--;
num2[index] += val;
n2[num2[index]]++;
}

int count(int tot) {
int res = 0;
for(auto& n : n1) {
res += n.second * n2[tot - n.first];
}

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);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/16/PS/LeetCode/finding-pairs-with-a-certain-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.