我们建立一个哈希表,其键值表示物品价值,其值为对应价值物品的重量之和。依次遍历 items}_1 和 items}_2 中的每一项物品,同时更新哈希表。最后,我们取出哈希表中的每一个键值对放入数组,对数组按照 value 值排序即可。
有些语言可以在维护键值对的同时,对键值对按照「键」进行排序,比如 C++ 中的 std::map,这样我们可以省略掉最后对数组的排序过程。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8
classSolution: defmergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: map = Counter() for a, b in items1: map[a] += b for a, b in items2: map[a] += b returnsorted([a, b] for a, b inmap.items())
publicclassSolution { public IList<IList<int>> MergeSimilarItems(int[][] items1, int[][] items2) { IDictionary<int, int> dictionary = new Dictionary<int, int>(); foreach (int[] v in items1) { dictionary.TryAdd(v[0], 0); dictionary[v[0]] += v[1]; } foreach (int[] v in items2) { dictionary.TryAdd(v[0], 0); dictionary[v[0]] += v[1]; }
IList<IList<int>> res = new List<IList<int>>(); foreach (KeyValuePair<int, int> kv in dictionary) { int k = kv.Key, v = kv.Value; res.Add(new List<int>{k, v}); } ((List<IList<int>>) res).Sort((a, b) => a[0] - b[0]); return res; } }
staticintcmp(constvoid *pa, constvoid *pb) { int *a = *(int **)pa; int *b = *(int **)pb; return a[0] - b[0]; }
int** mergeSimilarItems(int** items1, int items1Size, int* items1ColSize, int** items2, int items2Size, int* items2ColSize, int* returnSize, int** returnColumnSizes) { HashItem *mp = NULL; for (int i = 0; i < items1Size; i++) { hashSetItem(&mp, items1[i][0], items1[i][1] + hashGetItem(&mp, items1[i][0], 0)); } for (int i = 0; i < items2Size; i++) { hashSetItem(&mp, items2[i][0], items2[i][1] + hashGetItem(&mp, items2[i][0], 0)); } int len = HASH_COUNT(mp); int **res = (int **)malloc(sizeof(int *) * len); for (int i = 0; i < len; i++) { res[i] = (int *)malloc(sizeof(int) * 2); } int pos = 0; HashItem *pEntry = NULL; for (pEntry = mp; pEntry != NULL; pEntry = pEntry->hh.next) { res[pos][0] = pEntry->key; res[pos][1] = pEntry->val; pos++; } qsort(res, len, sizeof(int *), cmp); *returnSize = len; *returnColumnSizes = (int *)malloc(sizeof(int) * len); for (int i = 0; i < len; i++) { (*returnColumnSizes)[i] = 2; } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var mergeSimilarItems = function(items1, items2) { const map = newMap(); for (const v of items1) { map.set(v[0], (map.get(v[0]) || 0) + v[1]); } for (const v of items2) { map.set(v[0], (map.get(v[0]) || 0) + v[1]); }
const res = []; for (const [k, v] of map.entries()) { const pair = []; pair.push(k); pair.push(v); res.push(pair); } res.sort((a, b) => a[0] - b[0]); return res; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcmergeSimilarItems(item1, item2 [][]int) [][]int { mp := map[int]int{} for _, a := range item1 { mp[a[0]] += a[1] } for _, a := range item2 { mp[a[0]] += a[1] } var ans [][]int for a, b := range mp { ans = append(ans, []int{a, b}) } sort.Slice(ans, func(i, j int)bool { return ans[i][0] < ans[j][0] }) return ans }