Table of Contents
一、中文版
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
二、英文版
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
三、My answer
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# version 1: 两层 for 循环,大数据会超时
# for i in range(len(nums)):
# for j in range(len(nums)):
# if i != j and (nums[i] + nums[j] == target):
# return [i,j]
# version 2:借助 dictionary,遍历一次数组,边遍历边存入 dictionary
# _dict = {}
# for i in range(len(nums)):
# if (target - nums[i]) in _dict:
# return [i,_dict[target - nums[i]]]
# else:
# _dict[nums[i]] = i
# version 3:使用 enumerate() 改进 version 2
_dict = {}
for i,num in enumerate(nums):
if (target - num) in _dict:
return [i,_dict[target - num]]
else:
_dict[num] = i
四、解题报告
version 2 的精髓是把谁存入 dictionary?是把遍历过的数 num 存入 dictionary,而不是需要配对的数(target - num)存入,因为遍历过的数(num)不会再回头重新遍历,之后有可能遇到的也只是需要配对的数(target - num),此时需要查的是 num 是否在dictionary,所以 dictionary 中存的是 num 和 下标。
两数之和是经典题目,此题有很多变种,比如要求返回求和等于 target 的两个数值,则可以改为如下:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums.sort()
i = 0
j = len(nums) - 1
while i < j:
if nums[i] + nums[j] == target:
return [i,j]
elif nums[i] + nums[j] < target:
i += 1
else:
j -= 1