LeetCode第1题:Two_Sum

Question:

1.Given an array of integers, return indices of the two numbers such that they add up to a specific target.

2.You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:


Analyze:

1、我们的目的是获取list中满足要求的index,考虑使用字典将满足条件的value和index映射起来。

2、首先创建一个空字典,用于传入列表中的值。然后遍历列表中的值(number),遍历的同时,我们可以计算出这个值需要的另一个值(加数),如本题中target=9,则number=5对应的另一个值就为4(9-5=4)。如果4不在字典中,则将number及其在列表中的索引映射并存入字典,再重复遍历判断,直到遍历到的值在字典中也恰好存在。

Code:

class Solution:
    def twoSum(self,nums,target):
        if len(nums) <= 1: #ensure two elements at least
            return False
        num_dict = {} 
        for i,number in enumerate(nums):
            try:
                return [num_dict[target-number],i] #return index
            except:
                num_dict[number] = i #update dict

Result:

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值