LeetCode每日1题--两个数组的交集

65 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情

前言

算法的重要性不言而喻!区分度高!

现在学习的门槛低了,只有能上网每个人都可以学编程!培训班6个月就可以培养出来能干活的人,你怎么从这些人中脱颖而出?没错!就是学算法,学一些底层和基础的东西。

说的功利点是为了竞争,卷死对手。真心话说就是能提高自己的基础能力,为技术可持续发展做好充分的准备!!!

提前入门学习书籍:CPrimerPlus、大话数据结构

image-20220705103735001

刷题网站

代码随想录 (programmercarl.com)

leetcode

我是按照代码随想录提供的刷题顺序进行刷题的,大家也可以去刷leetcode最热200道,都可以

刷题嘛,最重要的就是坚持了!!!

画图软件

OneNote

这个要经常用,遇见不懂的流程的话就拿它画一画!

笔记软件

Typoral

题目

解析

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

image.png

暴力

暴力法的话就是遍历两个数组,然后比较它们相等的话把这个元素放到一个新的集合中去,这样集合收集的就是两个数组的交集。这里时间复杂度为n的平方

依旧是hash

这里不能直接使用hash结构,而是使用了hashset,因为使用hash这个数据结构的前提是元素的个数是确定的,而这里很明显不知道数组有多少个元素 代码如下:

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<Integer>();
        Set<Integer> set2 = new HashSet<Integer>();
        for (int num : nums1) {
            set1.add(num);
        }
        for (int num : nums2) {
            set2.add(num);
        }
        return getIntersection(set1, set2);
    }
​
    public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
        if (set1.size() > set2.size()) {
            return getIntersection(set2, set1);
        }
        Set<Integer> intersectionSet = new HashSet<Integer>();
        for (int num : set1) {
            if (set2.contains(num)) {
                intersectionSet.add(num);
            }
        }
        int[] intersection = new int[intersectionSet.size()];
        int index = 0;
        for (int num : intersectionSet) {
            intersection[index++] = num;
        }
        return intersection;
    }
}

为什么不用集合呢?

还是前面说的,如果使用数组来做哈希相关的题目,题目一定会限制数组的大小

而且如果哈希值比较少、特别分散、跨度非常大,使用数组就造成空间的极大浪费。

遇到哈希问题都用set不就得了,用什么数组啊?

占用空间更多了呗,速度比数组慢。而且set它把数值映射到key上还需要进行hash计算这样是很耗费时间的,数据量大的情况,差距是很明显的。

哈希小总结

快速判断一个元素是否出现在集合的时候,就要考虑哈希算法!

如果使用哈希集合存储元素,则可以在O(1) 的时间内判断一个元素是否在集合中,从而降低时间复杂度。

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);
            }
        }
        int[] resArr = new int[resSet.size()];
        int index = 0;
        //将结果几何转为数组
        for (int i : resSet) {
            resArr[index++] = i;
        }
        return resArr;
    }
}

\