Two Sum(python)两数相加

题目:Two Sum

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

第一步:用 zip 函数做一个字典,将nums中数字与index联系起来:

In [33]: dictionary = dict(zip(nums, list(range(0, len(nums)))))
In [34]: dictionary
Out[34]: {2: 0, 7: 1, 11: 2, 15: 3}

第二步:循环将 target 减去 nums 中的 value, 得到一个subvalue, 如果这个subvalue在字典里面, 就返回 value和subvalue的 index 

完整程序如下:

calss Solution():
    def twosum(nums, target):
        dictionary = dict(zip(nums, list(range(0, len(nums)))))
        for index, value in enumerate(num):
            subvalue = target - value
            if sub in dic:
                return [index, dictionary[subvalue]]
            else:
                continue

也可循环生成字典(此种解法是别人写的,代码里面有其详细地址),此种解法如下:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = dict()
        for index,value in enumerate(nums):
            sub = target - value
            if sub in dic:
                return [dic[sub],index]
            else:
                dic[value] = index #此处循环生成字典,效果和我上面程序的dictionary一样

作者:石晓文的学习日记
链接:https://www.jianshu.com/p/b71fc7307e42
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值