要求:1.给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。
2.假设每个输入只有一个解决方案,并且不会两次使用相同的元素。
例子:Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
代码:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return ([i,j])
run time:5596ms
best:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hmap = {}
for i, num in enumerate(nums):
if num in hmap:
return [hmap[num], i]
else:
hmap[target-num] = i
runtime:36ms
思路:新建空字典
将列表中第一个元素与target差值作为键,元素索引作为对应值插入字典hmap={target-num[0] : 0}
loop{
判断列表中元素是否为字典中的键(寻找列表中是否有与各元素所需差值相等的元素值):
是:返回该键的值(列表索引)以及当前元素索引
否:将当前元素与target差值(要得到target,当前元素需要加上的值)作为键,元素索引作为对应值插入字典中
}
tips: 1. enumerate()函数使用
- 如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
print index, item
>>>
0 这
1 是
2 一个
3 测试
- enumerate还可以接收第二个参数,用于指定索引起始值,如:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
print index, item
>>>
1 这
2 是
3 一个
4 测试