[LeetCode] Merge Similar Items

2363. Merge Similar Items

You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties:

  • items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.
  • The value of each item in items is unique.

Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.

Note: ret should be returned in ascending order by value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<vector<int>> mergeSimilarItems(vector<vector<int>>& items1, vector<vector<int>>& items2) {
unordered_map<int, int> mp;
for(auto& A : items1) {
mp[A[0]] += A[1];
}
for(auto& A : items2) {
mp[A[0]] += A[1];
}
vector<vector<int>> res;
for(auto [k,v] : mp) res.push_back({k,v});
sort(begin(res), end(res));
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/07/PS/LeetCode/merge-similar-items/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.