1、两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
解法(最简单的):
利用两个for循环,遍历列表,找出两个元素值相加为target的元素下标。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if nums[i] + nums[j] == target:
return [i, j]
之后再更新进阶解法!
进阶:
将互补数与字典内数字进行比较,检查互补数是否在字典里,若在则说明索引i对应的数与字典某索引数相加为target,输出这两个索引即为目标值。
仅需要一次遍历数组(时间复杂度O(n)),平均情况下查找时间复杂度为O(1)。整体的时间复杂度保持在O(n),空间复杂度也是O(n)
思路:
创建一个空的字典,存储数字及索引,对于数组中的每个数num,计算它需要配对的数complement(即target - num)。然后检查这个complement是否已经存在于num_dict中。如果存在,说明之前遍历的某个数与当前数num的和等于target。由于num_dict[complement]存储了complement的索引,所以可以直接使用这个索引和当前的索引i返回结果。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_dict = {} # 用来存储数字及其索引
for i, num in enumerate(nums):
complement = target - num # 计算互补数
if complement in num_dict:
return [num_dict[complement], i] # 如果找到互补数,返回对应的索引
num_dict[num] = i # 否则,将当前数字及其索引存入字典
return [] # 如果没有找到任何匹配的元素对,返回空列表