力扣350

力扣350

记住Map的写法,put,remove,getOrDefault方法的使用
getOrDefault(key,defauit),如果在map中找不到key,则返回默认值。

善于使用散列表

Arrays.copyOfRange(intersection, 0, index)记住这个方法(复制0到index-1长度的数组);

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int num : nums1) {
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
        }
        int[] intersection = new int[nums1.length];
        int index = 0;
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0) {
                intersection[index++] = num;
                count--;
                if (count > 0) {
                    map.put(num, count);
                } else {
                    map.remove(num);
                }
            }
        }
        return Arrays.copyOfRange(intersection, 0, index);
    }
}

Set集合转换成int数组的做法,可先转换成Integer数组,再转换成int数组

//s1是hashset集合
Integer[] temp=s1.toArray(new Integer[]{});
        int[] num=new int[temp.length];
        for (int i=0;i<temp.length;i++){
            num[i]=temp[i];
        }
posted @ 2021-03-15 19:24  shaon111  阅读(42)  评论(0)    收藏  举报