# LeetCode1：Two Sum

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

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

/**
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> &numbers, int target) {
vector<int> resvec(2, 0);
if(numbers.empty())
return resvec;
unordered_map<int, int> imap;
int len = numbers.size();
//        for(int i = 0; i < len; i++)
//            imap[numbers[i]] = i+1;
for(int i = 0; i < len; i++)
{
//这里要注意，一开始，我直接利用数组元素初始化map，但会出现相同元素值覆盖的情况
if(imap.count(target - numbers[i]))
{
resvec[0] = imap[target - numbers[i]] + 1;
resvec[1] = i+1;
break;
}
imap[numbers[i]] = i;

}

return resvec;

}
};
int main(void)
{
int arr[] = {2,7,11,15};
vector<int> numbers(arr, arr+4);
Solution solution;
vector<int> resvec = solution.twoSum(numbers, 9);

vector<int>::iterator iter;
for(iter = resvec.begin(); iter != resvec.end(); ++iter)
cout<<*iter<<endl;

return 0;
}
-----------------------我和我追猪的梦-----------------------------------------------------------------

posted @ 2014-04-28 10:53  mickole  阅读(357)  评论(0编辑  收藏  举报