题目
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
records = dict()
for index,value in enumerate(nums):
if target - value not in records: //查找值
records[value]=index //保存当前元素的值和下标
else:
return [records[target - value],index]
基础知识
1. dict() 函数用于创建一个字典。
形式:{'key':'value'}
存储:dictionary[key] = item
如:
n = dict({'x': 1, 'y': 2})
print('n =',n)
n = {'x': 1, 'y': 2}
2.循环并获取元素下标
使用enumerate(枚举)函数:用于将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标。
index:下标 value:值
for index, value in enumerate(num):
print(index, value)
3.in 和 not in
in:用于判断键是否存在于字典中,如果键在字典 dict 里返回 true,否则返回 false。
not in:如果键在字典 dict 里返回 false,否则返回 true。
题目中,value为键,下标为值。