leecode算法《两个数组的交集》详解有注释,简单明了。

leecode算法《两个数组的交集》详解有注释,简单明了。

原题内容

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:

输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:此题比较呆萌的解决办法

幼稚的方法是根据第一个数组 nums1 迭代并检查每个值是否存在在 nums2 内。如果存在将值添加到输出。这样的方法会导致 O(n \times m)O(n×m) 的时间复杂性,其中 n 和 m 是数组的长度。
这样写面试官肯定会让你GG的
此方法比较简单不写代码;

解法一:此题正确的解决办法

将两个数组转换为集合 set,然后迭代较小的集合检查是否存在在较大集合中。平均情况下,这种方法的时间复杂度为 O(n+m)O(n+m)。
并且set还能去重
在这里插入图片描述
代码如下:

import java.util.*;

public class imooc {
    public static void main(String[] args) {
        Integer[] t1 = new Integer[]{1, 2, 3, 4, 4};
        Integer[] t2 = new Integer[]{1, 2, 67, 4, 9, 6};
        // 调用方法
        List<Integer> list = get(t2, t1);
        // 循环将结果输出chu来
        for (Integer i : list) {
            System.out.print(i);
        }
    }

    private static List<Integer> get(Integer[] t1, Integer[] t2) {
        // 创建两个Set存入数组中的元素
        // 将数组中的元素放入到Set中
        Set<Integer> hashSet1 = new HashSet<>(Arrays.asList(t1));
        Set<Integer> hashSet2 = new HashSet<>(Arrays.asList(t2));
        // 用来接收返回的数据
        List<Integer> list = new ArrayList<>();
        // 迭代较小的集合检查是否存在在较大集合中
        if (hashSet1.size() < hashSet2.size()) {
            for (Integer s : hashSet1) {
                if (hashSet2.contains(s)) {
                    list.add(s);
                }
            }
        } else {
            for (Integer s : hashSet2) {
                if (hashSet1.contains(s)) {
                    list.add(s);
                }
            }
        }
        return list;
    }
}

解法三:内置函数

内置的函数在一般情况下的时间复杂度是 O(n+m)O(n+m) 且时间复杂度最坏的情况是 O(n \times m)O(n×m) 。
在 Java 提供了 retainAll() 函数(次函数专门用来取交集的).

import java.util.*;

public class imooc {
    public static void main(String[] args) {
        Integer[] t1 = new Integer[]{1, 2, 3, 4, 4};
        Integer[] t2 = new Integer[]{1, 2, 67, 4, 9, 6};
        // 调用方法
        List<Integer> list = get2(t2, t1);
        // 循环将结果输出chu来
        for (Integer i : list) {
            System.out.print(i);
        }
    }
    private static List<Integer> get2(Integer[] t1, Integer[] t2) {
        // 创建两个Set存入数组中的元素
        // 循环将数组中的元素放入到Set中
        Set<Integer> hashSet1 = new HashSet<>(Arrays.asList(t1));
        Set<Integer> hashSet2 = new HashSet<>(Arrays.asList(t2));
        // 用retainAll内置函数进行取交集结果会返回到hashSet1中。
        hashSet1.retainAll(hashSet2);
        // 返回 List。
        return new ArrayList<>(hashSet1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值