两个数组的交集

打印 上一主题 下一主题

主题 897|帖子 897|积分 2691

利用数据布局Set

我们定义一个Set集合,先去遍历数组nums1,        让其内部全部元素都存储到这个set集合中,然后再去遍历nums2,假如nums2中的元素在set集合中包含了,则阐明这是两个数组都有的
  1. import java.util.*;
  2. class Solution {
  3.     public int[] intersection(int[] nums1, int[] nums2) {
  4.         // if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
  5.         //     return new int[0];
  6.         // }
  7.         Set<Integer> set1 = new HashSet<>();
  8.         Set<Integer> resSet = new HashSet<>();
  9.         //遍历数组1
  10.         for (int i : nums1) {
  11.             set1.add(i);
  12.         }
  13.         //遍历数组2的过程中判断哈希表中是否存在该元素
  14.         for (int i : nums2) {
  15.             if (set1.contains(i)) {
  16.                 resSet.add(i);
  17.             }
  18.         }
  19.       
  20.         //方法1:将结果集合转为数组
  21.         return resSet.stream().mapToInt(x -> x).toArray();
  22.     }
  23. }
复制代码
数组法

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

[code]import java.util.*;class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        //数组法来写        int[] temp=new int[1001];        Set list=new HashSet();        for(int i=0;i
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

乌市泽哥

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表