89 - 两个数组的交集
题目
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。
解答
可以写个双循环,不过这成本有些太高了;也可以存一个哈希表,空间换时间
set
官网提出了set的做法,可以先排除不一样的数
Runtime: 68 ms, faster than 22.11% of JavaScript online submissions for Intersection of Two Arrays.
Memory Usage: 36.4 MB, less than 7.69% of JavaScript online submissions for Intersection of Two Arrays.
出奇的慢。。
作者:zhl1232
这位大佬同样用set写出了不一样的解法
Runtime: 56 ms, faster than 77.57% of JavaScript online submissions for Intersection of Two Arrays.
Memory Usage: 34.3 MB, less than 53.85% of JavaScript online submissions for Intersection of Two Arrays.
很酷吼
感觉我绕远路了
Runtime: 4 ms, faster than 86.09% of Go online submissions for Intersection of Two Arrays.
Memory Usage: 4.5 MB, less than 100.00% of Go online submissions for Intersection of Two Arrays.
Last updated
Was this helpful?