美文网首页
两数之和 python

两数之和 python

作者: 吕阳 | 来源:发表于2019-03-18 23:51 被阅读0次
    • 执行用时为 28 ms 的范例
    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if len(nums)<=1:
                return None
            buff={}
            for i in range(len(nums)):
                if nums[i] in buff:
                    return [i,buff[nums[i]]]
                else:
                    buff[target-nums[i]]=i
    
    • 执行用时为 24 ms 的范例
    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            num_dict = {}
            for i, num in enumerate(nums):
                complement = target - num 
                if complement in num_dict:
                    return [num_dict[complement], i]
                num_dict[num] = i
    
    • 执行用时为 20 ms 的范例
    class Solution:
        # @return a tuple, (index1, index2)
        # 8:42
        def twoSum(self, nums, target):
            d={}
            for i,num in enumerate(nums):
                if target-num in d:
                    return d[target-num], i
                d[num]=i
    

    相关文章

      网友评论

          本文标题:两数之和 python

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