题目描述
给你两个二维整数数组 items1 和 items2 ,表示两个物品集合。每个数组 items 有以下特质:
- items[i] = [valuei, weighti] 其中 valuei 表示第 i 件物品的 价值 ,weighti 表示第 i 件物品的 重量 。
- items 中每件物品的价值都是 唯一的 。
请你返回一个二维数组 ret,其中 ret[i] = [valuei, weighti], weighti 是所有价值为 valuei 物品的 重量之和 。
注意:ret 应该按价值 升序 排序后返回。
示例
- 示例1:
输入:items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
输出:[[1,6],[3,9],[4,5]]
解释:
value = 1 的物品在 items1 中 weight = 1 ,在 items2 中 weight = 5 ,总重量为 1 + 5 = 6 。
value = 3 的物品再 items1 中 weight = 8 ,在 items2 中 weight = 1 ,总重量为 8 + 1 = 9 。
value = 4 的物品在 items1 中 weight = 5 ,总重量为 5 。
所以,我们返回 [[1,6],[3,9],[4,5]] 。
- 示例2:
输入:items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]
输出:[[1,4],[2,4],[3,4]]
解释:
value = 1 的物品在 items1 中 weight = 1 ,在 items2 中 weight = 3 ,总重量为 1 + 3 = 4 。
value = 2 的物品在 items1 中 weight = 3 ,在 items2 中 weight = 1 ,总重量为 3 + 1 = 4 。
value = 3 的物品在 items1 中 weight = 2 ,在 items2 中 weight = 2 ,总重量为 2 + 2 = 4 。
所以,我们返回 [[1,4],[2,4],[3,4]] 。
- 示例3:
输入:items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]
输出:[[1,7],[2,4],[7,1]]
解释:
value = 1 的物品在 items1 中 weight = 3 ,在 items2 中 weight = 4 ,总重量为 3 + 4 = 7 。
value = 2 的物品在 items1 中 weight = 2 ,在 items2 中 weight = 2 ,总重量为 2 + 2 = 4 。
value = 7 的物品在 items2 中 weight = 1 ,总重量为 1 。
所以,我们返回 [[1,7],[2,4],[7,1]] 。
- 提示:
- 1 <= items1.length, items2.length <= 1000
- items1[i].length == items2[i].length == 2
- 1 <= valuei, weighti <= 1000
- items1 中每个 valuei 都是 唯一的 。
- items2 中每个 valuei 都是 唯一的 。
解题
from collections import Counter
from itertools import chain
class Solution:
def mergeSimilarItems(self, items1: list[list[int]], items2: list[list[int]]) -> list[list[int]]:
# 循环遍历 items1 ,嵌套循环遍历 items2 ,items2 有的追加到 items1 并弹出,最后将没有的再与 items1 拼接在一起,排序。
# for i in range(0, len(items1)):
# for j in range(0, len(items2)):
# if items2[j][0] == items1[i][0]:
# items1[i][1] = items1[i][1] + items2[j][1]
# items2.pop(j)
# break
# items1 += items2
# items1.sort()
# return items1
#
# 第二种
# Counter() 是用于计算可哈希对象的字典子类。 它是一个集合,其中元素存储为字典键
# 它们的计数存储为字典值。允许计数
# 任何整数值,包括零计数或负计数。
cnt = Counter()
# itertools.chain(*iterables) 类似循环,创建一个迭代器,从第一个可迭代对象返回元素,直到它 用尽,
# 然后继续下一个可迭代对象,直到所有可迭代对象都已 用尽。用于将连续序列视为单个序列。
for v, w in chain(items1, items2):
cnt[v] += w
# return [[v, cnt[v]] for v in range(1, 1001) if cnt[v]]
return sorted(cnt.items())
s = Solution()
out = s.mergeSimilarItems([[1, 1], [4, 5], [3, 8]], [[3, 1], [1, 5]])
# s.mergeSimilarItems([[1, 1], [3, 2], [2, 3]], [[2, 1], [3, 2], [1, 3]])
print(out)