您的位置:首页 > 其它

Two Sum

2015-01-05 23:23 113 查看
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<map>
using namespace std;

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
//思路: 用target = a + b ====> a = target -b;
//利用hash 表 , 首先把每个数对应的下标存起来, 在map 里卖遍历一次就行。num1 = target - numb2(numb2 直接在数组中取就行了)
map<int , int > mapping;
vector<int> result;
for(int i = 0 ; i < numbers.size(); ++i)
{
mapping[numbers[i]] = i;
}//缓存每个数字对应的下标, 因为题目要求是要返回下标的。

for(int i = 0; i < numbers.size(); ++i)
{
const int num1 = target - numbers[i];
if((mapping.find(num1) != mapping.end()) && mapping[num1] != i)
{//19 行 如果没有加入 mapping[num1] != i 的话有个测试用例 比如 [3, 2 , 4] 就过不了,没加返回的是 1 1
result.push_back(i + 1);
result.push_back(mapping[num1] + 1);//因为是从0开始存储的, 所以返回下标的时候要 加上1;
break; //找到之后立马退出来。
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: