Skip to content

Commit d0e5a11

Browse files
add python solution for twoSum
1 parent f0e566a commit d0e5a11

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

algorithms/twoSum/twoSum-python.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
### twoSum(https://leetcode-cn.com/problems/two-sum)
2+
3+
**Python**
4+
5+
```python
6+
from typing import List
7+
8+
class Solution:
9+
def twoSum(self, nums: List[int], target: int) -> List[int]:
10+
d = {}
11+
n = len(nums)
12+
for i in range(n):
13+
if target - nums[i] in d:
14+
return d[target - nums[i]], i
15+
else:
16+
d[nums[i]] = i
17+
```
18+
19+
```
20+
### 复杂度分析
21+
22+
- 时间复杂度:O(n^2)
23+
> 每次循环都要遍历剩下的数组元素
24+
- 空间复杂度:O(1)
25+
> 没有占用额外的空间
26+
```
27+
28+
**复杂度分析**
29+
30+
- 时间复杂度: O(n)
31+
32+
> 我们只遍历了包含有 *n* 个元素的列表一次。在表中进行的每次查找只花费 O(1)*O*(1) 的时间。
33+
34+
- 空间复杂度:O(n)
35+
36+
> 所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 *n* 个元素。
37+

0 commit comments

Comments
 (0)