leetCode 349号题目详解 两个数组的交集 ,python3两种方式实现, 复杂度分别为O(n^2) 和 O(n)
2018-09-24 14:09
816 查看
[code]给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。
原题如上:
第一种暴力方法,双层遍历如代码 复杂度为O(n^2), 数量级标比较大就很慢
[code]class Solution: def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1, nums2 = list(set(nums1)), list(set(nums2)) back = [] for num2 in nums2: if num2 in nums1: back.append(num2) return back if __name__ == "__main__": a = Solution() nums1 = [1,3,2] nums2 = [3,3,4] print(a.intersection(nums1, nums2))
第二种方法, 把第一个数组倒置成一个元组, 就形成了索引, 速度自然就提高了
复杂度分析: 第一个数组遍历一次, 构建索引 复杂度O(n)
第二个数组遍历一次, 每次遍历比对第一个数组的key, 如果为1 表示存在, 这里复杂度是O(1)*O(n)
总公复杂度是O(n)+O(1)*O(n) = 2O(n) = O(n)
其中要注意的是, 要把第二个list取唯一值才能保证唯一
[code]class Solution: def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums2 = list(set(nums2)) back = [] dictNums1 = {} for num1 in nums1: dictNums1[num1] = 1 for num2 in nums2: if dictNums1.get(num2) == 1: back.append(num2) return back if __name__ == '__main__': a = Solution(); print(a.intersection([2,3,1,2,3], [3,2,3,4]))
阅读更多
相关文章推荐
- 第一次发博客,新手初试啊,题目如下:有两个10个元素的数组,分别为A和B,编程实现相同位置的元素, 如果 B 的元素小于 A 的元素进行数值交换:(使用回调函数实现)
- LeetCode--350. Intersection of Two Arrays II(两个数组的交集)Python
- [LeetCode] Binary Tree Level Order Traversal 与 Binary Tree Zigzag Level Order Traversal,两种按层次遍历树的方式,分别两个队列,两个栈实现
- 两个有序数组交集与并集的实现
- python实现合并两个数组的方法
- 用python求两个数组的交集
- Python: 数组条件过滤简洁实现方式
- LeetCode Median of Two Sorted Arrays 在两个已排列的数组中找出中位数。时间复杂度为O(log(min(N,M))
- LeetCode 87 Scramble String (Python详解及实现)
- python 获得两个数组(List)交集、并集与差集
- python实现合并两个数组的方法
- Python 两个列表的差集、并集和交集实现代码
- leetcode 将已排序的 数组/链表 转换为二叉搜索树(BST),Python实现
- LeetCode 73 Set Matrix Zeroes(Python详解及实现)
- LeetCode 92 Reverse Linked List II (Python详解及实现)
- 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。(Python实现)
- Leetcode:350. Intersection of Two Arrays II 求两个数组的交集
- 将任务4的解决用一个项目多个文件的方式实现,其中两个类的声明放在一个.h文件中,每个类的成员函数分别放一个文件,main()函数用一个文件。
- 有两个10个元素的数组,分别为A和B,编程实现相同位置的元素, 如果 B 的元素小于 A 的元素进行数值交换:(使用回调函数实现)
- 求两个数组的交集、并集和差集算法分析与实现