leetcode 1. 两数之和

遍历数组即可

时间复杂度:O(n)
空间复杂度:O(n)

1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_to_index = dict([(num, i) for i, num in enumerate(nums)])
for i, num in enumerate(nums):
expected_num_index = num_to_index.get(target-num)
if expected_num_index and expected_num_index > i:
return [i, expected_num_index]
return []