两数之和-leetcode(python)

记录下自己的做法,虽然完成的并不好,但还是分享一下。

题目:

给定一个整数数列,找出其中和为特定值的那两个数。

你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
注意 nums = [3,3],target = 6 return [0,1]
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for num in nums:
            sub = target-num
            if sub == num:
            	first_index = nums.index(num)
            	try:
            		second_index =nums.index(sub,first_index+1)
            	except ValueError:
            		continue
            	if second_index != first_index:
            		return [first_index,second_index]
            	else:
            		continue
            if sub in nums:
                return [nums.index(num),nums.index(sub)]


方法二:

> 每取一个数,就把对应要找的数加入到字典中,并记录数字的索引值。KEY为所需的数字,VALUE为索引值。取数是从前往后取,但是是跟之前取过的数字对应想要找到的数比较。

class Solution:  
    def twoSum(self,nums, target):  
        """ 
        :type nums: List[int] 
        :type target: int 
        :rtype: List[int] 
        """  
        #创建一个空字典  
        d = {}  
        for x in range(len(nums)):  
            a = target - nums[x]  
            if nums[x] in d:     #字典d中存在nums[x]时  
                return d[nums[x]],x  
            else:                #否则往字典增加键/值对 
                d[a] = x         #边往字典增加键/值对,边与nums[x]进行对比  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值