-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge-similar-items_2363.py
51 lines (40 loc) · 2.42 KB
/
merge-similar-items_2363.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 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.
# Example 1:
# Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]
# Output: [[1,6],[3,9],[4,5]]
# Explanation:
# The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.
# The item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.
# The item with value = 4 occurs in items1 with weight = 5, total weight = 5.
# Therefore, we return [[1,6],[3,9],[4,5]].
# Example 2:
# Input: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]
# Output: [[1,4],[2,4],[3,4]]
# Explanation:
# The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.
# The item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.
# The item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.
# Therefore, we return [[1,4],[2,4],[3,4]].
# Example 3:
# Input: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]
# Output: [[1,7],[2,4],[7,1]]
# Explanation:
# The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7.
# The item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.
# The item with value = 7 occurs in items2 with weight = 1, total weight = 1.
# Therefore, we return [[1,7],[2,4],[7,1]].
# ---------------------------------------Runtime 107 ms Beats 71.48% Memory 17.22 MB Beats 95.64%---------------------------------------
from typing import List
class Solution:
def mergeSimilarItems(
self, items1: List[List[int]], items2: List[List[int]]
) -> List[List[int]]:
items_map = {}
union = sorted((items1 + items2), key=lambda x: x[0])
for key, value in union:
items_map[key] = items_map.get(key, 0) + value
return items_map.items()