Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Note: The intersection of two arrays is defined as the set of elements that are present in both arrays.
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]Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = set()
for i in nums1:
for j in nums2:
if i == j:
res.add(i)
break
return list(res)Where is the size of the array and is the size of the array .
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
n, m = len(nums1), len(nums2)
res, i, j = [], 0, 0
while i < n and j < m:
while j < m and nums2[j] < nums1[i]:
j += 1
if j < m:
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
while i < n and nums1[i] == nums1[i - 1]:
i += 1
return resWhere is the size of the array and is the size of the array .
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
set1 = set(nums1)
set2 = set(nums2)
res = []
for num in set1:
if num in set2:
res.append(num)
return resWhere is the size of the array and is the size of the array .
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
seen = defaultdict(int)
for num in nums1:
seen[num] = 1
res = []
for num in nums2:
if seen[num] == 1:
seen[num] = 0
res.append(num)
return resWhere is the size of the array and is the size of the array .
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
seen = set(nums1)
res = []
for num in nums2:
if num in seen:
res.append(num)
seen.remove(num)
return resWhere is the size of the array and is the size of the array .
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))Where is the size of the array and is the size of the array .