leecode-两个数组的交集

 

 解答:

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length ==0) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int i : nums1) {
            set1.add(i);
        }
        for (int i : nums2) {
            if (set1.contains(i)) {
                set2.add(i);
            }
        }
    //通过stream()方法拿到流对象,mapToInt拿到Int流对象,就可以toArray返回int数组了
    //这里x->x是lambda表达式,对应一个函数式接口,因为集合中泛型为Interger类型,自动拆箱功能,所以直接返回x就行
    //如果这里式String泛型要转为int数组的话,就要调用Integer.parseInt()方法,lambda写法:mapToInt(Integer::parseInt)
        return set2.stream().mapToInt(x -> x).toArray();
    }
}

 

posted @ 2022-11-09 22:36  阿拉斯加没有眼泪  阅读(46)  评论(0)    收藏  举报