LeetCode第1题:Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Analyze: 

  1. 注意题目里的假设:each input would have exactly one solution,因此输出答案是唯一的,不会出现[ 3, 4, 5, 6 ]这样的数组:(3+6 = 4+5 = 9),所以优先考虑的是一次遍历
  2. 在一次遍历的同时,我们可以计算出这个数需要的另一个加数,记为checkNum,例如5的checkNum就是(9-5=)4。
  3. 判断当前数字是否在checkNum中,例如遍历到数字4的时候,发现有checkNum中恰好有一个4,则成功找到。

这里的难点就在于如何返回checkNum对应那个数字的下标,解决办法是:

创建一个solution_dict字典,字典的key是checkNum,value是当前数字在nums中的下标

Code:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        solution_dict = {}
        for i in range(len(nums)):
            if (nums[i] in solution_dict):  # if already exists
                return [solution_dict[nums[i]],i]
            else:   # renew the dictionary
                # calcu what we need 
                checkNum = target - nums[i]
                solution_dict[checkNum] = i

Result:

Runtime: 40 ms, faster than 86.49% of Python3 online submissions for Two Sum.

Memory Usage: 14.5 MB, less than 5.08% of Python3 online submissions for Two Sum.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值