首页 > 其他分享 >leecode-两个数组的交集

leecode-两个数组的交集

时间:2022-11-09 22:48:24浏览次数:40  
标签:mapToInt set2 交集 int leecode set1 数组 nums1 nums2

 

 解答:

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();     } }

 

标签:mapToInt,set2,交集,int,leecode,set1,数组,nums1,nums2
From: https://www.cnblogs.com/tianxiaocheng/p/16875475.html

相关文章