349.Intersection of Two Arrays
Tags: [set]
Link: https://leetcode.com/problems/intersection-of-two-arrays/\#/description
Given two arrays, write a function to compute their intersection.
Example:
Givennums1=[1, 2, 2, 1]
,nums2=[2, 2]
, return[2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
Solution: set
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if not nums1 or not nums2:
return []
nums1_set = set(nums1)
result_set = set()
for num in nums2:
if num in nums1_set:
result_set.add(num)
return [x for x in result_set]
Note:
- Time complexity = O(n + k), n is the length of nums1, and k is the length of nums2.