# 349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
# Solution
Approach 1: set/hashtable.
Approach 2: sort first then use two pointers.
# Code (Python)
Approach 1:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1) & set(nums2) # or a hashtable of all elements in nums1, then throw nums2 at it
Approach 2:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
intersection = []
p1, p2 = 0, 0
while p1 < len(nums1) and p2 < len(nums2):
if nums1[p1] < nums2[p2]:
p1 += 1
elif nums1[p1] > nums2[p2]:
p2 += 1
else:
if intersection and nums1[p1] == intersection[-1]:
p1 += 1
p2 += 1
else:
intersection.append(nums1[p1])
return intersection
# Code (C++)
Approach 1:
Approach 2: