Difficulty: Medium
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来做,真的比较简单,在题解的指点下敲了出来。
对于Vector,Map的使用更加熟练了一些。
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int, int> m;
int f,n;
for(int i =0; i<nums.size();i++){
m.insert(map<int, int> :: value_type(nums[i], i));
f = target - nums[i];
if(m.count(f)==1){
n = m[f];
if(i<n){
result.push_back(i+1);
result.push_back(n+1);
//cout<<f<<" "<<n<<endl;
return result;
}
if(i>n){
result.push_back(n+1);
result.push_back(i+1);
//cout<<n<<" "<<i<<endl;
return result;
}
}
}
}