给定两个数组,编写一个函数来计算它们的交集
(题目来源:力扣网)
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
方法:流式计算:
package com.lxf.demo01;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 方法:流式计算
*/
public class Intersection {
public static int[] intersection(int[] nums1, int[] nums2) {
List<Integer> temp = new ArrayList<Integer>();
Arrays.stream(nums1).distinct().forEach(num1->{
Arrays.stream(nums2).distinct().forEach(num2->{
if(num1==num2){
temp.add(num1);
}
});
});
Integer[] sames=new Integer[temp.size()];
return Arrays.stream(temp.toArray(sames)).mapToInt(Integer::valueOf).toArray();
}
public static void main(String[] args) {
//测试
int[] nums1 ={1,2,2,1}, nums2 = {2,2};
int[] intersection = intersection(nums1, nums2);
for (int i = 0; i < intersection.length; i++) {
System.out.print(intersection[i]);
}
}
}