给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
java实现
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
TreeSet<Integer> resSet1 = new TreeSet<>();
TreeSet<Integer> resSet2 = new TreeSet<>();
for (int i:nums1){
resSet1.add(i);
}
for (int j : nums2){
if (resSet1.contains(j)){
resSet2.add(j);
}
}
int [] res = new int[resSet2.size()];
int index = 0;
for(int val : resSet2){
res[index] = val;
index++;
}
return res;
}
}
python实现
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set([i for i in nums1 if i in nums2]))