算法笔记: 力扣#349 两个数组的交集

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
class :
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class :
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set()
for num in nums2:
if num in set1:
set2.add(num)
return list(set2)

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for(int n : nums1){ set1.add(n); }
for(int n : nums2){
if(set1.contains(n)){
set2.add(n);
}
}
int[] ans = new int[set2.size()];
int i = 0;
for(int val : set2)
ans[i++] = val;
return ans;
}
}

时间复杂度

O(m+n).

空间复杂度

O(m+n).

链接


349. Intersection of Two Arrays
349. 两个数组的交集
(English version) Algorithm Notes: Leetcode#349 Intersection of Two Arrays