Leetcode原题链接:两数之和
一、一般题解
暴力解法,排列组合遍历解决。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return i,j
时间复杂度O(n²)。
二、哈希表解法
- 准备一个字典,存放遍历的数:{数值:下标}。
- 从第一个数开始遍历,寻找 target 减当前数值是否存在于字典中,存在则返回下标,不存在则继续遍历。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = {}
for idx, val in enumerate(nums):
if target - val not in records:
records[val] = idx
else:
return idx, records[target-val]
*enumerate()功能:
- enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
- 举例:
例1:
nums = ['one', 'two', 'three', 'four']
for index,value in enumerate(nums):
print(index, value)
0 one
1 two
2 three
3 four
例2:
nums = {
'a': 'one',
'b': 'two',
'c': 'three',
'd': 'four'
}
for i, j in enumerate(nums):
print(i, j)
0 a
1 b
2 c
3 d
例3:
nums = {
'a': 'one',
'b': 'two',
'c': 'three',
'd': 'four'
}
for i, j in enumerate(nums.values()):
print(i, j)
0 one
1 two
2 three
3 four