美文网首页
001-Two Sum

001-Two Sum

作者: 篮子always | 来源:发表于2017-12-27 11:14 被阅读8次

    语言: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循环效率更

    相关文章

      网友评论

          本文标题:001-Two Sum

          本文链接:https://www.haomeiwen.com/subject/dfnygxtx.html