001-Two Sum

语言:python3


v1:轮询

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]

结果:超时了,提交失败

v2:建立字典,循环字典

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i in range(len(nums)):
            if not nums[i] in d:
                d[nums[i]] = i   #保存数组位置信息
            if target - nums[i] in d:
                if d[target - nums[i]] < i:  #防止 6-3=3的情况
                    return [d[target - nums[i]], i]

总结:字典映射结构比for循环效率更

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • [TOC] P001 Two Sum Given an array of integers, return ind...
    hylexus阅读 2,361评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,314评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,043评论 25 709
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 11,092评论 0 4
  • 先生出差了,朋友问去了哪里,我说吉林。长春?朋友说。我用了问号,但朋友确实是用肯定的语气“说”的。 我不由想,如果...
    不是一棵葱就是一瓣蒜阅读 3,382评论 0 1