查看原文
其他

两数之和算法讨论,附中秋赠书获奖读者

XksA 简说Python 2019-05-25

一、说在前面

昨天和今天的讨论中我们(由于中秋佳节之际,这次群内只有我和两位学长讨论)优化算法的点主要是在:数据结构上,也就是,到底用什么数据结构存储数据,遍历最快?

我们常见的几种数据结构:列表、元组、字典、枚举,在上一篇推文[【边学边敲边记】LeetCode001:两数之和]中我们已经使用了列表、字典作为存储载体,结果是字典遍历要快很多,今天我将介绍另外两种数据存储结构的执行效果。

二、实现

  • 元组数据结构

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        l = len(nums)
        tuple_nums = tuple(nums)
        for a in range(l):
            one_unm = tuple_nums[a]
            other_one = target - one_unm
            if other_one in tuple_nums:
                b = tuple_nums.index(other_one)
                if a!= b:
                    return [a,b]

nums = [3312]
target = 6
test_o = Solution()
result = test_o.twoSum(nums,target)
print(result)
  • 提交结果

提交结果

测试数据:29组
运行时间:888ms
击败人百分比:64.24%

  • 枚举数据结构


class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        nums_hash = {}
        for index,number in enumerate(nums):
            one_num = nums[index]
            other_num = target-one_num
            if other_num in nums_hash:
                return [nums_hash[other_num],index]
            nums_hash[number] = index
        return []
  • 提交结果

提交结果

测试数据:29组
运行时间:28ms
击败人百分比:98.70%

从中可以看出,字典和枚举的遍历效率要高于列表和元组的,原因是什么呢?

光城学长的解释(为光城学长点赞,昨天中秋之际,仍然坚持分享心得思想):

和字典一样,枚举类 Enum 是可以作为 HashMap 的key的,都有键值对(key-value),这就是他们比列表、元组遍历快很多的原因,而且数据量越大,越明显。

三、附录

中秋节送书活动获奖名单如下:

麻烦以上两位读者【 喡 和 鸿雁】在9.26中午12:30前联系我,未联系视为放弃,书籍将分享到读者交流群。

在此,再次感谢章书院对本次赠书活动支持。

END

往期精彩

今天,有句话和大家说

【边学边敲边记】LeetCode001:两数之和

Jupyter 安装使用教程

Python 抓取「知识星球」精华并生成电子书

教科书式数据库学习:带你学会三大主流数据库

进学习交流群

扫码加X先生微信进学习交流群[福利多多]

温馨提示

欢迎大家转载,转发,留言,点赞支持X先生。

文末广告点一下也是对X先生莫大的支持。

做知识的传播者,随手转发。


更多精彩推荐,请关注我们


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存