mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
简化 0001.两数之和.md python代码
原代码过于赘余,需要遍历两次且可读性较差。更新后的代码在维持题主题意的基础上的一次优化
This commit is contained in:
@ -110,13 +110,14 @@ Python:
|
|||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||||
hashmap={}
|
records = dict()
|
||||||
for ind,num in enumerate(nums):
|
|
||||||
hashmap[num] = ind
|
# 用枚举更方便,就不需要通过索引再去取当前位置的值
|
||||||
for i,num in enumerate(nums):
|
for idx, val in enumerate(nums):
|
||||||
j = hashmap.get(target - num)
|
if target - val not in records:
|
||||||
if j is not None and i!=j:
|
records[val] = idx
|
||||||
return [i,j]
|
else:
|
||||||
|
return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user