最近,在用解决LeetCode问题的时候,做了349: Intersection of Two Arrays这个问题,就是求两个列表的交集。我这种弱鸡,第一种想法是把问题解决,而不是分析复杂度,于是写出了如下代码:

 class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
ret = []
for i in nums1:
if i in nums2 and not i in ret:
ret.append(i)
return ret

打眼一看,嗯,挺好,时间负责度是O(n),点击提交,AC;打开结果一看,EXM?才击败了15%?这是O(n*2)的复杂度啊!哪里有问题呢?再一看,问题就出在i in nums2这个语句中了,在Python中,List的in操作的时间复杂度是O(n),也就是实现的算法复杂度果然是O(n2)了。看来只是单纯的看表面的循环的复杂度是不行的,还是要了解一些内部的实现。等等,这是两个列表的交集操作啊,集合才是完美的实现,python自带了集合类型set。嗯,就用集合了,又写了如下代码:

 class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1).intersection(set(nums2)))

提交,AC,查看结果,beat 80%,果然快了好多,代码还更加Pythonic了。对于Python的各种数据类型的时间复杂度,可以看这里。写代码的过程中,要充分了解Python的内部实现,才能运行的更快啊!

然后又看到了350. Intersection of Two Arrays II,这次的结果是两个数组的交集,但是可以有重复元素了,要运行O(n)的话,这次直接想到了用空间换时间,无非是使用hash了,Python的字典就是hash实现的,于是写了:

 class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
tmp_dict = dict()
ret = []
for i in nums1:
tmp_dict[i] = tmp_dict[i] + 1 if tmp_dict.get(i) else 1
for n in nums2:
if tmp_dict.get(n) > 0:
ret.append(n)
tmp_dict[n] -= 1
return ret

提交运行,果然,击败了90%。结果不错,但是我还是想到用Python的Countrs了,这样会不会更快呢?点击打开讨论区,果然看到有这样用的:

 class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
a, b = map(collections.Counter, (nums1, nums2))
return list((a & b).elements())

代码更短了,对于熟悉Counters的人来说,也更好理解了,不过运行效率也没有提升。至于哪种方式好,就是另外一个问题了。

Python 解LeetCode:Intersection of Two Arrays的更多相关文章

  1. [LeetCode] Intersection of Two Arrays II 两个数组相交之二

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  2. [LeetCode] Intersection of Two Arrays 两个数组相交

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  3. LeetCode Intersection of Two Arrays

    原题链接在这里:https://leetcode.com/problems/intersection-of-two-arrays/ 题目: Given two arrays, write a func ...

  4. LeetCode Intersection of Two Arrays II

    原题链接在这里:https://leetcode.com/problems/intersection-of-two-arrays-ii/ 题目: Given two arrays, write a f ...

  5. [LeetCode&Python] Problem 350. Intersection of Two Arrays II

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  6. [LeetCode&Python] Problem 349. Intersection of Two Arrays

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  7. 【leetcode❤python】350. Intersection of Two Arrays II

    #-*- coding: UTF-8 -*- class Solution(object):    def intersect(self, nums1, nums2):                ...

  8. Python 解leetcode:48. Rotate Image

    题目描述:把一个二维数组顺时针旋转90度: 思路: 对于数组每一圈进行旋转,使用m控制圈数: 每一圈的四个元素顺时针替换,可以直接使用Python的解包,使用k控制每一圈的具体元素: class So ...

  9. Python 解LeetCode:671. Second Minimum Node In a Binary Tree

    题目在这里,要求一个二叉树的倒数第二个小的值.二叉树的特点是父节点的值会小于子节点的值,父节点要么没有子节点,要不左右孩子节点都有. 分析一下,根据定义,跟节点的值肯定是二叉树中最小的值,剩下的只需要 ...

随机推荐

  1. Paint the Grid Reloaded ZOJ - 3781 图论变形

    Paint the Grid Reloaded Time Limit: 2000MS   Memory Limit: 65536KB   64bit IO Format: %lld & %ll ...

  2. The Twin Towers zoj2059 DP

    The Twin Towers Time Limit: 2 Seconds      Memory Limit: 65536 KB Twin towers we see you standing ta ...

  3. vim环境设置(应用于python编程)

    1. 安装完整的vim # apt-get install vim-gnome 2. 安装ctags,ctags用于支持taglist,必需! # apt-get install ctags 3. 安 ...

  4. python常见模块命令(os/sys/platform)

    一.Os Python的标准库中的os模块主要涉及普遍的操作系统功能.可以在Linux和Windows下运行,与平台无关. os.sep 可以取代操作系统特定的路径分割符. os.name字符串指示你 ...

  5. HDU2874 LCA Tarjan

    不知道为什么_add2不能只用单方向呢...........调试了好多次,待我解决这个狗血问题 #include <iostream> #include <vector> #i ...

  6. Hadoop(五)搭建Hadoop与Java访问HDFS集群

    前言 上一篇详细介绍了HDFS集群,还有操作HDFS集群的一些命令,常用的命令: hdfs dfs -ls xxx hdfs dfs -mkdir -p /xxx/xxx hdfs dfs -cat ...

  7. 我的第一个python web开发框架(7)——本地部署前端访问服务器

    PS:本系列内容进度节奏会放的很慢,每次知识点都尽量少一点,这样大家接触的知识点少了,会更容易理解,因为少即是多.另外,对于后面代码部分,虽然尽量不用那些复杂的封装和类,但它并不表示看了就能全部记住, ...

  8. git的使用(进阶篇)

    如何处理代码冲突 冲突合并一般是因为自己的本地做的提交和服务器上的提交有差异,并且这些差异中的文件改动,Git不能自动合并,那么就需要用户手动进行合并 如我这边执行git pull origin ma ...

  9. MIRO做发票校验时实现替代功能的多种方式

    http://blog.sina.com.cn/s/blog_3f2c03e30100ngje.html MIRO做发票校验时,如果需要对产生的会计凭证做某些字段的替代,可有多种方法. 1.GGB1替 ...

  10. HTML5之window.applicationCache对象

    不知道离线缓存技术的可以参照上一篇文章: HTML5之appcache语法理解/HTML5应用程序缓存/manifest缓存文件官方用法翻译 参考文章 window.applicationCache  ...