方法一,暴力:
from typing import List 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] return []方法二:
def twoSum(nums, target): lens = len(nums) j=-1 for i in range(lens): if (target - nums[i]) in nums: if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):#如果num2=num1,且nums中只出现了一次,说明找到是num1本身。 continue else: j = nums.index(target - nums[i],i+1) #index(x,i+1)是从num1后的序列后找num2 break if j>0: return [i,j] else: return []方法二,改进:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): temp = nums[:i] num1 = target - nums[i] if num1 in temp: j = temp.index(num1) return [i,j]方法三,使用哈希表(耗时最短):
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """ :type nums: List[int] :type target: int :rtype: List[int] """ map_a = dict() k = len(nums) for i in range(0, k): #一边将列表中的数添加到字典中,一边判断两数之差是否存在于字典中 temp = target - nums[i] if temp in map_a : # 判断步骤 return [map_a[temp], i] map_a[nums[i]] = i # 添加步骤(切记先判断再添加,以免key冲突)参考 python之哈希表 菜鸟-python字典