1.考虑不重复元素,重复元素不添加
import java.awt.List;
import java.util.ArrayList;
import java.util.TreeSet;
public class Solution {
public static int[] intersection(int[] nums1,int[] nums2){
TreeSet set =new TreeSet<>();
for(int num : nums1)//把不重复的nums1加入到集合中
set.add(num);
ArrayList list=new ArrayList<>();
for(int num:nums2){
if(set.contains(num)){
list.add(num);
set.remove(num);
}
}
int[] res=new int[list.size()]
for(int i=0;i
res[i]=list.get(i);
return res;
}
public static void main(String[] args) {
int[] nums1={1,2,2,1};
int[] nums2={2,2};
System.out.println("shuju"+intersection(nums1,nums2));
}
}
2.重复元素添加
import java.util.ArrayList;
import java.util.TreeMap;
public class Solution1 {
public static int[] intersect(int[] nums1, int[] nums2) {
TreeMap map = new TreeMap<>();
for (int num : nums1) {
if (!map.containsKey(num)) // 不包含
map.put(num, 1); // 出现频率
else
map.put(num, map.get(num) - 1);
}
ArrayList list = new ArrayList<>();
for (int num : nums2) {
if (map.containsKey(num)) {
list.add(num);
map.put(num, map.get(num) - 1);
if (map.get(num) == 0)
map.remove(num);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++)
res[i] = list.get(i);
return res;
}
}