Skip to content

Commit bfbf3e5

Browse files
authored
Create 0350 Intersection of Two Arrays II.md
1 parent 7458c63 commit bfbf3e5

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# 350. Intersection of Two Arrays II
2+
https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
3+
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
4+
5+
Example 1:
6+
Input: nums1 = [1,2,2,1], nums2 = [2,2]
7+
Output: [2,2]
8+
9+
Example 2:
10+
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
11+
Output: [4,9]
12+
Explanation: [9,4] is also accepted.
13+
14+
Constraints:
15+
1 <= nums1.length, nums2.length <= 1000
16+
0 <= nums1[i], nums2[i] <= 1000
17+
18+
19+
Follow up:
20+
What if the given array is already sorted? How would you optimize your algorithm?
21+
What if nums1's size is small compared to nums2's size? Which algorithm is better?
22+
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
23+
24+
``` python3
25+
class Solution:
26+
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
27+
hashtable1=dict()
28+
hashtable2=dict()
29+
ans=[]
30+
for i in nums1:
31+
if i in hashtable1.keys():
32+
hashtable1[i]+=1
33+
else:
34+
hashtable1[i]=1
35+
for i in nums2:
36+
if i in hashtable2.keys():
37+
hashtable2[i]+=1
38+
else:
39+
hashtable2[i]=1
40+
for i in hashtable1.keys():
41+
if i in hashtable2.keys():
42+
ans+=[i]*min(hashtable2[i],hashtable1[i])
43+
return ans
44+
```

0 commit comments

Comments
 (0)