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
Solution in C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> Map;
vector<int> answer;
for(int i=0; i<nums.size(); i++){
if(Map.find(target-nums[i])!=Map.end()){
answer.push_back( Map[target-nums[i]]+1);
answer.push_back(i+1);
break;
}else{
Map[nums[i]] = i;
}
}
return answer;
}
};
Note: C++中map是小写的。。赋值可以直接Map[]=..
vector在声明时可以规定初始大小,如vector<int> answer(2)就初始化了一个大小为2的vector,这是answer中下标为0和1的位置都默认用0填充,这时如果再push_back新的元素,则下标会从2,3开始算,因为0和1内已经有东西了。但如果用answer[0]=和answer[1]=来改变0和1单元的值,则不会增加vector的size。
C++中好多类和函数都是小写的,比如map,vector,min,max
但NULL是大写的