一.问题描述
给定一个整数数组 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].
二.解决思路
先排序,排序之后用两个指针分别指向头和尾,头尾相加如果>target,说明右边的数大了,尾指针向左动一格
主要问题是:
1.排序过程中会丢失原来的位置索引,通过用字典对nums的值和位置做一个映射
2.两个数相同的时候,字典的处理。通过将字典值设为向量来解决,字典和向量的结合要注意一下
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起讨论一起刷题一起ac
三.源码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
left=0
right=len(nums)-1
num_map={}
for i in range(0,len(nums)):
#pay attention to this step, how to deal with the combination of list and dic
num_map.setdefault(nums[i],[]).append(i)
nums.sort()
while left<right:
if nums[left]+nums[right]>target:
right-=1
elif nums[left]+nums[right]<target:
left+=1
else :
if nums[left]==nums[right]:
return [num_map[nums[left]][0],num_map[nums[left]][1]]
else:
return [num_map[nums[left]][0],num_map[nums[right]][0]]