Leetcode #1 2sum

题目

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].

思路:取出一个数n,再从剩下的数中寻找target-n,使用一趟hash即可。

class Solution:
    def twoSum(self, nums, target):
        """ :type nums: List[int] :type target: int :rtype: List[int] """

        result = {}
        for idx, i in enumerate(nums): # 一定要是当前的index,防止[3,3] 返回[0,0]的情况
            tmp = target - i
            if tmp in result:

                return [result[tmp], idx]
            result[i] = nums.index(i)
        return 'no solution'

这里只考虑一组解的情况,输出所有结果的如下:

待续

点赞