Leetcode 2363. Merge Similar Items
You are given two 2D integer arrays items1
and items2
, each of which contains item[i] = [value, weight]
representing the value
and weight
of the i-th
item.
value
and weight
?items1
and items2
?value
?items
within each input array guaranteed to be unique based on their value
?Let’s write a C++ solution for merging the items and summing the weights for items with the same value.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<int>> mergeSimilarItems(vector<vector<int>>& items1, vector<vector<int>>& items2) {
unordered_map<int, int> itemMap;
// Process the first array
for (const auto& item : items1) {
itemMap[item[0]] += item[1];
}
// Process the second array
for (const auto& item : items2) {
itemMap[item[0]] += item[1];
}
// Collect the results
vector<vector<int>> result;
for (const auto& [value, weight] : itemMap) {
result.push_back({value, weight});
}
// Sort the result based on the value
sort(result.begin(), result.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
});
return result;
}
// Helper function for demonstrating the output
void printItems(const vector<vector<int>>& items) {
for (const auto& item : items) {
cout << "[" << item[0] << ", " << item[1] << "] ";
}
cout << endl;
}
int main() {
vector<vector<int>> items1 = \{\{1, 3}, {2, 2}, {3, 1}};
vector<vector<int>> items2 = \{\{2, 3}, {3, 2}, {4, 1}};
vector<vector<int>> mergedItems = mergeSimilarItems(items1, items2);
printItems(mergedItems);
return 0;
}
items1
and items2
, updating the hash table.items1
and items2
respectively.Overall, the time complexity is (O(n + m + k \log k)).
Feel free to ask any further questions or for additional modifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?