Skip to content

Commit 42b5c19

Browse files
committed
week1 homewor1
1 parent 0fd6bbe commit 42b5c19

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Week01/1.两数之和.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#
2+
# @lc app=leetcode.cn id=1 lang=python3
3+
#
4+
# [1] 两数之和
5+
#
6+
7+
# @lc code=start
8+
class Solution:
9+
def twoSum(self, nums: List[int], target: int) -> List[int]:
10+
"""
11+
1 暴力,两轮遍历,和 = target
12+
O(N*2) O(1) 没用额外数组等
13+
2 用字典,一轮遍历,生成字典;第二轮遍历,如果 target - num 在 num前面的值列表中
14+
O(N) O(N)
15+
3 用字典,一轮遍历,如果 target - num 在 字典中!!!不要用列表,慢,就返回,否则就加到字典当中
16+
O(N) O(N)
17+
436ms if ano_num in nums[:idx]:
18+
68ms if ano_num in num_idx_dict: 这个还是快非常多的!!!
19+
字典:用字典存储,一一对应查找最快,用空间换时间~
20+
"""
21+
22+
if len(nums) < 2: return False
23+
num_idx_dict = {}
24+
25+
for idx, num in enumerate(nums):
26+
# 表示另一个数字another_num
27+
ano_num = target - num # 错误:如果放在语句里,记得加括号!
28+
# 如果another_num num在字典中,就是所求结果,返回索引
29+
if ano_num in num_idx_dict: # !!!
30+
return [num_idx_dict[ano_num], idx]
31+
# 否则就加到字典中
32+
num_idx_dict[num] = idx
33+
34+
35+
# @lc code=end
36+
37+
38+
# s = Solution()
39+
# print(s.twoSum([2,7,11,15], 9))

0 commit comments

Comments
 (0)