[leetcode:python]1.Two Sum

来源:互联网 发布:孪生素数c语言 编辑:程序博客网 时间:2024/06/05 22:51

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

使用字典存放数值和索引.

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        lookup = {}        for i, num in enumerate(nums):            if target - num in lookup:                return [lookup[target - num], i]            lookup[num] = i        return []

enumerate()函数:
enumerate字典上是枚举、列举的意思。
python文档中是这么说的:

enumerate(sequence, [start=0])
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which sup-
ports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing
a count (from start which defaults to 0) and the corresponding value obtained from iterating over iter-
able. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), ….

For example:

for i, season in enumerate([’Spring’, ’Summer’, ’Fall’, ’Winter’]):

print i, season
0 Spring
1 Summer
2 Fall
3 Winter

0 0