两个数组的交集 II (Intersection of Two Arrays II)

 

思路:

// @Title: 两个数组的交集 II (Intersection of Two Arrays II)
// @Author: qisiii
// @Date: 2021-08-16 16:26:00
// @Runtime: 2 ms
// @Memory: 38.8 MB
// @comment: 
// @flag: 
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        ArrayList<Integer> result=new ArrayList<Integer>();
        HashMap<Integer,Integer> nums1Map=new HashMap<>();
            for (int i : nums1) {
                Integer num=nums1Map.get(i);
                if (num==null){
                    nums1Map.put(i,1);
                }else {
                    nums1Map.put(i,num+1);
                }
            }
            for (int i : nums2) {
                Integer count=nums1Map.get(i);
                if (count!=null&&count>0){
                    result.add(i);
                    nums1Map.put(i,count-1);
                }
            }
            int[] r=new int[result.size()];
            int count=0;
            for (Integer i : result) {
                r[count++]=i.intValue();
            }
            return r;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18