Given two arrays, write a function to compute their intersection.
Notice
- Each element in the result must be unique.
- The result can be in any order.
Have you met this question in a real interview?
Yes
Example
Givennums1=[1, 2, 2, 1]
,nums2=[2, 2]
, return[2]
.
def intersection(self, nums1, nums2):
# write your code here
if not nums1 or not nums2:
return []
hash = set()
ans = []
for num in nums1:
if num not in hash:
hash.add(num)
for num in nums2:
if num in hash:
ans.append(num)
hash.remove(num)
return ans