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
两种解法:Map和排序。
1.Map:
<K, V>为<值,下标>,map中保存的是已经扫描过的number。
这是一种很直观很自然的做法:
对于numbers[i],如果map中存在K=target-numbers[i],则要求的解为V(K=target-numbers对应的)和i;如果不存在,则向map中添加<numbers[i], i>。
2.排序:
numbers按非递减排序,设置两个游标idx1和idx2.
初始时,idx1指向第一个number,idx2指向最后一个number。
如果numbers[idx1]+numbers[idx2]==target,则要求的解为numbers[idx1]在原数列中的下标(现在的numbers是已经排序后的)和numbers[idx2]在原数列中的下标;
如果numbers[idx1]+numbers[idx2]>target,则idx2--;
如果numbers[idx1]+numbers[idx2]<target,则idx1++。
P.S.
这个题目最后要求的下标是以1为基准的,是实际的数组下标+1。
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; map<int,int> numbersMap; map<int,int>::iterator iter; for(int i=0;i<numbers.size();i++) { iter=numbersMap.find(target-numbers[i]); if(iter!=numbersMap.end()) { res.push_back(iter->second); res.push_back(i+1); break; } else { numbersMap[numbers[i]]=i+1; } } return res; } };