# 拿什么拯救你，我的面试之——从零打卡刷Leetcode（No.001）

No.1 Two Sum

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.

``````Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

``````def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
result.append(i)
result.append(j)
return result

``````def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i in range(len(nums)):
oneNum = nums[i]
twoNum  = target - oneNum
if twoNum in nums:
j = nums.index(twoNum)
if i != j:
result.append(i)
result.append(j)
return result

``````def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 创建字典一，存储输入列表的元素值和对应索引
num_dict = {nums[i]:i for i in range(len(nums))}
print(num_dict)
# 创建另一个字典，存储target-列表中的元素的值，小詹称为num_r吧，好表达
num_dict2 = {i:target-nums[i] for i in range(len(nums))}
print(num_dict2)
# 判断num_r是否是输入列表中的元素，如果是返回索引值，不是则往下进行
result = []
for i in range(len(nums)):
j = num_dict.get(num_dict2.get(i))
if (j is not None) and (j!=i):
result = [i,j]
break
return result

Python系列之——在北京当房奴的日子~