python twoSum
时间: 2025-03-11 10:03:26 浏览: 30
Python 实现 Two Sum 问题
对于 Two Sum
问题的一种更优解法是利用字典来存储所有数对的索引[^1]。这种方法能够有效地减少时间复杂度,使得算法效率更高。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
d = {}
for x in range(n):
a = target - nums[x]
if nums[x] in d:
return [d[nums[x]], x]
else:
d[a] = x
另一种方法则是通过双重循环遍历列表中的每一对元素并检查它们相加是否等于目标值[^2]。然而这种暴力求解的方法虽然简单直观但是性能较低,在数据量较大时不推荐使用。
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
for i in range(0, length):
for j in range(i + 1, length):
if nums[i] + nums[j] == target:
return [i, j]
上述两种方案均适用于 Python 3.9 及以上版本[^3]。
相关推荐


















