LeetCode 15  Intersection of Two Arrays
Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.


Note:
Each element in the result must be unique.
The result can be in any order.
Solution


A set
only allows unique values. The key here is to create a set
for both nums1
and nums2
and then return the intersection of the two sets. unique_nums1 & unique_nums2
returns another set
so it is important to convert that to a list
.
Time complexity O(n)
because you need to run through both nums1
and nums2
.
Space complexity O(n)
because you need to allocate a set for each of the two arrays.
Apparently according to the fastest solutions on LeetCode, you can trim this down to a oneliner return list(set(nums1) & set(nums2))
.