Skip to content

Commit b9bb493

Browse files
Add files via upload
1 parent 98af799 commit b9bb493

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

双指针/350.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
'''
2+
Descripttion: 两个数组的交集 II
3+
version: 1
4+
Author: Jason
5+
Date: 2020-11-22 16:58:35
6+
LastEditors: Jason
7+
LastEditTime: 2020-11-22 16:59:35
8+
'''
9+
10+
import random
11+
from typing import List
12+
13+
14+
def GenerateRandomList(number, size):
15+
temp = list()
16+
random_legth = random.randint(0, size)
17+
current_length = 0
18+
while current_length < random_legth:
19+
temp.append(random.randint(1, number))
20+
current_length += 1
21+
return temp
22+
23+
24+
class Solution:
25+
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
26+
res = list()
27+
nums1.sort()
28+
nums2.sort()
29+
p1 = 0
30+
p2 = 0
31+
while p1 < len(nums1) and p2 < len(nums2):
32+
if nums1[p1] == nums2[p2]:
33+
res.append(nums1[p1])
34+
p1 += 1
35+
p2 += 1
36+
elif nums1[p1] < nums2[p2]:
37+
p1 += 1
38+
else:
39+
p2 += 1
40+
return res
41+
42+
def intersect2(self, nums1: List[int], nums2: List[int]) -> List[int]:
43+
from collections import defaultdict
44+
dict1 = defaultdict(int)
45+
dict2 = defaultdict(int)
46+
res = list()
47+
for each in nums1:
48+
dict1[each] += 1
49+
50+
for each in nums2:
51+
dict2[each] += 1
52+
53+
for each_key in dict1:
54+
if dict2[each_key] != 0:
55+
nums = min(dict1[each_key], dict2[each_key])
56+
res.extend([each_key] * nums)
57+
return res
58+
59+
60+
s = Solution()
61+
for _ in range(10):
62+
nums1 = GenerateRandomList(4, 12)
63+
nums2 = GenerateRandomList(4, 12)
64+
print(s.intersect2(nums1, nums2))
65+
print(s.intersect(nums1, nums2))

0 commit comments

Comments
 (0)