题目链接
https://leetcode-cn.com/problems/two-sum
题目原文
中文
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
English
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].
思路方法
方法一:暴力解决
直接进行两次循环,遍历所有配对,直到找到合适的一对
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
l = len(nums)
for i in range(l-1):
for j in range(i+1,l):
if nums[i]+nums[j] == target:
return [i,j]
方法二:利用哈希(字典)
创建一个字典,把nums中的每个数字依次加入字典中,同时查询target-nums[i]是否在字典里,在的话就提取index。
这里不需要考虑nums中有重复数字的问题。因为如果target等于两重复数字之和,那么在第二个重复数字进入字典之前,就已经return了,如果target不等于重复数字之和,第二个重复数字进入字典时,会覆盖第一个重复数字的index,不影响结果。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
lookup = {}
for i in range(n):
tmp = target - nums[i]
if tmp in lookup:
return [lookup[tmp], i]
lookup[nums[i]] = i
第一次写优快云,开心开心!