-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_intersection.py
More file actions
51 lines (42 loc) · 1.23 KB
/
Copy patharray_intersection.py
File metadata and controls
51 lines (42 loc) · 1.23 KB
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
#
#
# given two arrays with integers, return the intersection
#
#
def intersection(a :list, b: list) -> list :
if not a or not b :
return []
nums1_map = {}
nums2_map = {}
ret_list = []
for i in a :
nums1_map[i] = 1
for j in b :
if j in nums1_map :
nums2_map[j] = 1
return list(nums2_map.keys())
#print(f"elem map: {elem_map}, return list : {ret_list}")
def intersection_2(nums1: list, nums2: list) -> list:
if not nums1 or not nums2 :
return []
nums_map = {}
ret_list = []
for i in nums1 :
if i in nums_map :
nums_map[i] += 1
else :
nums_map[i] = 1
for j in nums2 :
if j in nums_map :
if nums_map[j] >= 1 :
ret_list.append(j)
nums_map[j] -= 1
return ret_list
test_lists = [
[ [0, 0, 5, 9 , 12, 1], [ 9, 1, 3], [9, 1] ],
[ [-1, 15, 4 , 1, 1], [ 15, 8, 9, 10, 3], [15] ],
[ [2, 2, 3, 3, 4, 5] , [2, 2] , [2]] ,
[ [-1, 1, 2, 2, 3, 3, 4, 5, 5 ,5] , [-7, 2, 2, 0, 5, 5] , [2]] ,
]
for t in test_lists :
print(f'input a: {t[0]}, input b: {t[1]}, output : {intersection_2( t[0], t[1])}')