Description:
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].
考察的点:
1.映射关系:映射关系有列表list 和字典dict,列表通过编号(按顺序)访问各个值,字典通过名称(不按顺序)访问其值。
2.基本的字典操作:
d[k]=v 将值v关联到键k
k in d 检查字典d是否包含键为k的项。
3.难点:
表达式 k in d(其中d是一个字典)查找的是键而不是值!!!
class Solution:
def twoSum(self, nums, target):
seen={} #empty dict
for i,n in enumerate(nums):
other=target-n
if other in seen: #'other' is a key,not a value
return[seen[other],i] #seen[other] returns a value,actually a index
else:
seen[n]=i #将没用的放入到字典中,到了真有用的才能正确计数,否则seen[other]返回的是0,
print(seen)
print("*"*10)
nums=[2,7,11,15]
target=26
t=Solution()
t.twoSum(nums,target)
class Solution:
def twoSum(self, nums, target):
dict={}
for i in range(len(nums)):
print(i)
if target-nums[i] not in dict:
dict[nums[i]]=i #nums[i] is a key ,i is a value
else:
return [dict[target-nums[i]],i] #now dict[target-nums[i]] 是倒数第二个,i is the last one.
print(dict)
print("*"*10)
nums=[2,7,11,15]
target=26
t=Solution()
t.twoSum(nums,target)