题目:
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
题意:
给定一个数组,从中找出两个数相加等于target,假设只有一组这样的数。函数返回这两个数的下标,且下标1要小于下标2.
解题思路:
1.因为要找下标,所以不能对数组先进行排序,这时有两种方法,一种是用两个循环遍历,但是会超时。另一种办法,使用map;
2.循环遍历数组,如果第i个数不在map中,将其加入map。并检测(target-第i个数)是否在map中,如果在,那么(target-第i个数)所对应下标即是另外一个数。
代码: