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即可,講一下容易出錯(cuò)的地方:
trap: 給的序列可能是重復(fù)的,所以我選擇用兩個(gè)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;
}