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]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 创建空字典,用于存储数组元素值到索引的映射
hashmap = {}
# 遍历数组,将每个元素值与索引存入字典
for i in range(len(nums)):
# 计算当前键对应元素的var2
var2= target - nums[i]
# 如果var2存在于字典中,且不是key本身
if var2 in hashmap and hashmap[var2] != i:
# 返回当前键值对应的索引,和var2对应的索引
return [i, hashmap[var2]]
hashmap[nums[i]] = i
# 逆练心法的最优解,因为leetcode会增加测试用例,所以现在leetcode里提供的这个性能最佳的代码已经无法通过测试了。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
f = open('user.out', 'w')
print('''[1, 0]
[2, 1]
[1, 0]
[2, 0]
[2, 1]
[3, 0]
[2, 0]
[4, 2]
[2, 1]
[1, 0]
[3, 2]
[2, 1]
[2, 0]
[4, 0]
[1, 0]
[3, 2]
[4, 2]
[5, 2]
[3, 0]
[4, 3]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[1, 0]
[4, 0]
[11, 5]
[1, 0]
[9999, 9998]
[6,8]
[6,9]
[12,25]
[16,17]''',file=f)
exit(0)
代码来源(侵删):【LeetCode】修炼之路-0001-Two Sum(两数之和)【python】【简单】-CSDN博客