乌市泽哥 发表于 2024-8-2 21:10:34

两个数组的交集

利用数据布局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;
      // }
      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;      Set list=new HashSet();      for(int i=0;i
页: [1]
查看完整版本: 两个数组的交集