1865: Finding-Pairs-With-a-Certain-Sum
Medium
table of contents
The first solution I thought of occured when I saw the
restraints for nums1
and nums2
.
After seeing that 1 <= nums1.length <= 1000
and
1 <= nums2.length <= 10^5
, there must exist a
solution which revolved around placing all nums2
elements
into a hashmap, then iterating through
nums1
(since it is wayyyyy smaller) to see how many of the
corresponding number in nums2
exists.
Therefore,
code
class FindSumPairs {
public:
<int> arr1;
vector<int> arr2;
vector<int, int> mp;
unordered_map(vector<int>& nums1, vector<int>& nums2) {
FindSumPairs= nums1;
arr1 = nums2;
arr2 for (int& num : arr2) {
++mp[num];
}
}
void add(int index, int val) {
--mp[arr2[index]];
[index] += val;
arr2++mp[arr2[index]];
}
int count(int tot) {
int ans = 0;
for (int& num : arr1) {
int difference = tot-num;
if (mp.count(difference)) {
+= mp[difference];
ans }
}
return ans;
}
};
/**
* Your FindSumPairs object will be instantiated and called as such:
* FindSumPairs* obj = new FindSumPairs(arr1, arr2);
* obj->add(index,val);
* int param_2 = obj->count(tot);
*/
complexity
learnings
if (mp.count(difference)) {
+= mp[difference];
ans }