您的位置:首页 > 编程语言 > Python开发

[leetcode:python]1.Two Sum

2017-05-10 11:28 387 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: