# 【记录帖】（No.001）从零打卡刷Leetcode

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系列之——在北京当房奴的日子~

468 篇文章50 人订阅

0 条评论

## 相关文章

43540

31760

7410

28640

16950

43830

36230

### BZOJ 3670: [Noi2014]动物园【KMP变形 】

3670: [Noi2014]动物园 Time Limit: 10 Sec  Memory Limit: 512 MB Submit: 2738  Solve...

37170

14520

### 《笨办法学Python》 第35课手记

《笨办法学Python》 第35课手记 本节课讲函数和分支的，实际上是一次综合练习，代码有点长，请先纠正代码中的错误使脚本能够运行。 原代码中使用三个空格来进行...

232100