[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:
使用字典存放数值和索引.
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
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
相关文章推荐
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- leetcode-001-two sum-python
- leetcode python - Two Sum
- Python leetcode记录(1) -Two Sum
- LeetCode 1.Two Sum (Python)
- 【LeetCode with Python】 Two Sum
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- (python)leetcode刷题笔记 01 TWO SUM
- LeetCode-two sum:python解答数组问题
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode]-[Two Sum]-python实现
- [leetcode, python] Two Sum 两数之和等于某数
- [leetcode, python] Two Sum 两数之和等于某数
- 【LeetCode】Two Sum 解题报告(java & python)
- python- leetcode - Two Sum
- [leetcode, python] Two Sum 两数之和等于某数