LeetCode Two Sum

来源:互联网 发布:淘宝双十一h5页面 编辑:程序博客网 时间:2024/05/22 12:02

 

题目描述:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

大意:两个参数,一个vector int,一个int target,寻找a+b=target(题目中最后一句每个target都会有一个结果,说明必然存在),返回a,b的索引,并不是a,b的value。

 

解题思路:1,用到map容器,这样就能将key value和index联系起来,返回满足条件的两个index

        2,遍历整个numbers即可

代码部分:
 

 

代码分析:

1,题目已经排除了numbers中有相等值的情况了,例如【4,4,1】,5,此时就会有问题。You may assume that each input would have exactly one solution.

2,注释掉的是参考别人的代码,思路就是从第一个开始遍历,找到就返回,找不到,就判断遍历到的该值是否存在,map不存在就存入。直到找到。

3, 其实没必要判断遍历到的numbers【i】是否存在,因为如果找不到target-numbers【i】,那么就应该将numbers【i】存入,因为每个numbers都不等

4,遍历的过程中,可以先存,再检查(就是代码中的for循环);也可以先检查,再存(注释掉的部分);不同点:先存入的话,就从numbers【1】开始;先检查的话就从numbers【0】开始。归根到底一样的,因为从0开始检查的话,也是先存了numbers【0】,接着检查的target-numbers【1】;

0 0
原创粉丝点击