两个数组的交集
  FHUfYd9S4EP5 2024年08月07日 38 0

使用数据结构Set

我们定义一个Set集合,先去遍历数组nums1, 让其内部所有元素都存储到这个set集合中,然后再去遍历nums2,如果nums2中的元素在set集合中包含了,则说明这是两个数组都有的

import java.util.*;
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> resSet = new HashSet<>();
        //遍历数组1
        for (int i : nums1) {
            set1.add(i);
        }
        //遍历数组2的过程中判断哈希表中是否存在该元素
        for (int i : nums2) {
            if (set1.contains(i)) {
                resSet.add(i);
            }
        }
      
        //方法1:将结果集合转为数组

        return resSet.stream().mapToInt(x -> x).toArray();
    }
}

数组法

这道题中有要求,两个数组的长度都控制在了1000以内,我们可以定义一个长度为1001的数组temp,遍历nums1,让其中的元素所对应temp数组下标的位置元素置为1,然后再去遍历nums2,如果nums2中的元素所对应temp中的下标位置的元素已经为1了,说明这是两者共有的元素,加入到一个Set集合中

import java.util.*;
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        //数组法来写
        int[] temp=new int[1001];
        Set<Integer> list=new HashSet<>();
        for(int i=0;i<nums1.length;i++){
            temp[nums1[i]]=1;
        }
        for(int i=0;i<nums2.length;i++){
            if(temp[nums2[i]]==1){
                list.add(nums2[i]);
            }
        }
        int[] result=list.stream().mapToInt(Integer::intValue).toArray();
        return result;
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年08月07日 0

暂无评论

推荐阅读
  FHUfYd9S4EP5   2天前   19   0   0 Java
  sSh3rBaiME5f   3天前   22   0   0 Java
  qCe06rFCa8NK   2天前   15   0   0 Java
  ZTo294hNoDcA   2天前   19   0   0 Java
  FHUfYd9S4EP5   2天前   16   0   0 Java
  QGiRIwDaZAe8   3天前   18   0   0 Java
FHUfYd9S4EP5