题目链接: 349. 两个数组的交集
难度:简单



这个题我是用两个Set解决,因为要元素唯一,就想到Set
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> s1 = new HashSet<>();
Set<Integer> rets = new HashSet<>();
for(int n:nums1){
s1.add(n);
}
for(int n: nums2){
if(s1.contains(n))
rets.add(n);
}
int[] nums = new int[rets.size()];
int i = 0;
for(int n:rets)
nums[i++] = n;
return nums;
}
}
当时一开始想复杂了,用了两个map一个set,也是够浪费的。🐷
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer,Integer> m1 = new TreeMap<>();
Map<Integer,Integer> m2 = new TreeMap<>();
Set<Integer> s = new HashSet<>();
for(int n:nums1){
m1.put(n,n);
}
for(int n:nums2){
m2.put(n,n);
}
int i = 0;
if(m1.size() <= m2.size()){
for(int n: m1.keySet()){
if(m2.containsKey(n))
s.add(n);
}
int[] num = new int[s.size()];
int index = 0;
for (int n: s ) {
num[index++] = n;
}
return num;
}else{
for(int n: m2.keySet()){
if(m1.containsKey(n))
s.add(n);
}
int[] num = new int[s.size()];
int index = 0;
for (int n: s ) {
num[index++] = n;
}
return num;
}
}
}