class Solution: def twoSum(self, nums, target): d = dict() for num, i in enumerate(nums): if target - num in d: return [d[target - num], i] d[nums[i]] = i return []这个代码运行错误
时间: 2024-02-14 15:05:08 浏览: 63
twoNumberSum.cpp
这个代码运行错误的原因可能是因为 `num` 和 `i` 的顺序写反了,应该是 `i, num`,即:
```python
class Solution:
def twoSum(self, nums, target):
d = dict()
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[nums[i]] = i
return []
```
另外,也可以使用 `num` 作为字典的 key,而不是 `nums[i]`,即:
```python
class Solution:
def twoSum(self, nums, target):
d = dict()
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
return []
```
这两种写法都是正确的,具体选择哪一种取决于个人喜好。
阅读全文