File tree Expand file tree Collapse file tree 2 files changed +29
-1
lines changed Expand file tree Collapse file tree 2 files changed +29
-1
lines changed Original file line number Diff line number Diff line change 11
11
12
12
既然是配对,那么 kv 结构是非常合适的,于是上了 Hash 表。让 key 就是要找的 ` b ` ,让 value 记录 ` a ` 的 index,也就是结果需要的索引。
13
13
14
- 这样思路就很简单明了了。
14
+ 这样思路就很简单明了了。
15
+
16
+ ## Python
17
+
18
+ 基本与 C++ 的思路一致,只不过更简洁了。
Original file line number Diff line number Diff line change
1
+ #!python3
2
+
3
+
4
+ class Solution :
5
+ def twoSum (self , nums , target ):
6
+ """
7
+ :type nums: List[int]
8
+ :type target: int
8FB5
code>
9
+ :rtype: List[int]
10
+ """
11
+ dic = {}
12
+ for index , num in enumerate (nums ):
13
+ if num in dic :
14
+ return [dic [num ], index ]
15
+ dic [target - num ] = index
16
+
17
+
18
+ if __name__ == "__main__" :
19
+ nums = [2 , 7 , 11 , 15 ]
20
+ target = 9
21
+ assert (Solution ().twoSum (nums , target ) == [0 , 1 ])
22
+ nums = [3 , 2 , 4 ]
23
+ target = 6
24
+ assert (Solution ().twoSum (nums , target ) == [1 , 2 ])
You can’t perform that action at this time.
0 commit comments