【Leetcode】001TwoSum


问题描述:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

例子

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

暴力求解
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            tmp = target - nums[i]
            #print(tmp)
            for j in range(i+1,len(nums)):
                if  tmp == nums[j]:
                    #print(i,j)
                    return i,j

s = Solution()
nums = [2,7,11,15]
# nums =[3,2,4]
target= 13
s.twoSum(nums,target)
效率分析

Runtime: 3296 ms, faster than 29.56% of Python online submissions for Two Sum.
Memory Usage: 12.5 MB, less than 81.85% of Python online submissions for Two Sum.

哈希表
		dict = {nums[i]:i for i in range(len(nums))}#注意到这里将原本的值作为键了,0、1、2、3作为
        # dict = {i:nums[i] for i in range(length)}

        for i in range(len(nums)):
            tmp = target - nums[i]
            j = dict.get(tmp)#根据keys找values
            if j!= None and j!=i:
                print(i,j)
                return i,j
效率分析

Runtime: 32 ms, faster than 82.89% of Python online submissions for Two Sum.
Memory Usage: 13.3 MB, less than 13.56% of Python online submissions for Two Sum.

final
        for i in range(len(nums)):
            tmp = target - nums.pop(0)
            if tmp in nums:
                return [i,nums.index(tmp)+i+1]
效率分析

Runtime: 776 ms, faster than 39.69% of Python online submissions for Two Sum.
Memory Usage: 12.6 MB, less than 77.88% of Python online submissions for Two Sum.

2019_6_2
keys = {}
        for i in range(len(nums)):
            if target-nums[i] in keys:
                return [keys[target-nums[i]],i]
            if nums[i] not in keys:
                keys[nums[i]] = i

Runtime: 36 ms, faster than 80.16% of Python online submissions for Two Sum.
Memory Usage: 13 MB, less than 55.66% of Python online submissions for Two Sum.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值