Skip to content

Commit 06e5349

Browse files
committed
Intersection of Two Arrays II
1 parent 869c264 commit 06e5349

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

350-intersection-of-two-arrays-ii.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/intersection-of-two-arrays-ii/
3+
4+
Given two arrays, write a function to compute their intersection.
5+
6+
Example 1:
7+
Input: nums1 = [1,2,2,1], nums2 = [2,2]
8+
Output: [2,2]
9+
10+
Example 2:
11+
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
12+
Output: [4,9]
13+
14+
Note:
15+
Each element in the result should appear as many times as it shows in both arrays.
16+
The result can be in any order.
17+
18+
Follow up:
19+
What if the given array is already sorted? How would you optimize your algorithm?
20+
What if nums1's size is small compared to nums2's size? Which algorithm is better?
21+
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements
22+
into the memory at once?
23+
"""
24+
class Solution(object):
25+
def intersect(self, nums1, nums2):
26+
"""
27+
:type nums1: List[int]
28+
:type nums2: List[int]
29+
:rtype: List[int]
30+
"""
31+
dic = {}
32+
for a in nums1:
33+
dic[a] = dic.get(a, 0) + 1
34+
res = []
35+
for a in nums2:
36+
if a in dic and dic[a] > 0:
37+
res.append(a)
38+
dic[a] -= 1
39+
return res

0 commit comments

Comments
 (0)