Question: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
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
本题比较简单,用hashmap即可,讲一下容易出错的地方:
trap: 给的序列可能是重复的,所以我选择用两个map
//
// main.cpp
// leetcode
//
// Created by YangKi on 15/11/11.
// Copyright © 2015年 YangKi. All rights reserved.
//
#include<cstdlib>
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
unordered_map<int, int> map2;
vector<int>ans;
int size=nums.size();
for(int i=0; i<size; i++)
{
if(map.find(nums[i]) == map.end())
{
map[ nums[i] ]= (i+1);
}
else//duplicate
{
map2[ nums[i] ]=(i+1);
}
}
for(int i=0; i<size; i++)
{
if( map.find(target-nums[i]) != map.end() )//success
{
if(nums[i] == target-nums[i])
{
if(map2.find(nums[i]) != map2.end() )
{
ans.push_back(min(map[nums[i]], map2[nums[i]]));
ans.push_back(max(map[nums[i]], map2[nums[i]]));
break;
}
else
{
continue;
}
}
else
{
ans.push_back(min(map[nums[i]], map[target-nums[i]]));
ans.push_back(max(map[nums[i]], map[target-nums[i]]));
}
break;
}
}
return ans;
}
};
int main()
{
Solution *s=new Solution();
vector<int>v={2,7,11,15};
vector<int>vv=s->twoSum(v, 9);
printf("%d %d\n", vv[0], vv[1]);
return 0;
}