当前位置:   article > 正文

给定两个数组,编写一个函数来计算它们的交集。_函数中两个数组能计算吗

函数中两个数组能计算吗

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:

输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

  1. class Solution {
  2. public int[] intersection(int[] nums1, int[] nums2) {
  3. Set<Integer> set = new HashSet<>();
  4. Set<Integer> res = new HashSet<>();
  5. for(int n : nums1)
  6. set.add(n);
  7. for(int n : nums2)
  8. if(set.contains(n))
  9. res.add(n);
  10. int[] result = new int[res.size()];
  11. int index = 0 ;
  12. for(int n : res)
  13. result[index++] = n;
  14. return result;
  15. }
  16. }
  1. class Solution {
  2. public int[] intersection(int[] nums1, int[] nums2) {
  3. return Arrays.stream(nums1).filter(x -> Arrays.stream(nums2).anyMatch(x2 -> x==x2)).distinct().toArray();
  4. }
  5. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/775722
推荐阅读
相关标签
  

闽ICP备14008679号