[LeetCode] Merge Two 2D Arrays by Summing Values

2570. Merge Two 2D Arrays by Summing Values

You are given two 2D integer arrays nums1 and nums2.

  • nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.
  • nums2[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.

Each array contains unique ids and is sorted in ascending order by id.

Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:

  • Only ids that appear in at least one of the two arrays should be included in the resulting array.
  • Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be 0.

Return the resulting array. The returned array must be sorted in ascending order by id.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {
map<int, int> mp;
for(auto n : nums1) {
int id = n[0], val = n[1];
mp[id] += val;
}
for(auto n : nums2) {
int id = n[0], val = n[1];
mp[id] += val;
}
vector<vector<int>> res;
for(auto [k,v] : mp) res.push_back({k,v});
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/19/PS/LeetCode/merge-two-2d-arrays-by-summing-values/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.