使用数据结构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;
    }
}