题意:给定两个数组,编写一个函数来计算它们的交集。
说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class SSS {
    public  List<Integer> intersection(int[] nums1, int[] nums2) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int num : nums1){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        List<Integer> intersection = new ArrayList<>();
        for(int num : nums2){
            if(map.containsKey(num) && map.get(num)>0){
                intersection.add(num);
                map.put(num,map.get(num)-1);
            }
        }
        return intersection;
    }
    public static void main(String[] args) {
        int[] nums1 = {1,2,3,5,2,1};
        int[] nums2 = {2,3,5,2,2};
        SSS sss = new SSS();
        List<Integer> result = sss.intersection(nums1, nums2);
        System.out.println(result); // [2,2]
    }
}



















![buu web [强网杯 2019]随便注](https://img-blog.csdnimg.cn/538b12bc39e6446b8919b0d14a9e84fd.png)