利用数据布局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集合中
[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 |