您的位置:首页 > 其它

[LeetCode]Two Sum

2013-10-08 13:36 281 查看
Two Sum

这题思路很简单,创建一个hash table,用来存放访问过的数值和对应的位置。从头到尾循环,假如hash table里面有匹配的数值,则取出对应的数值的位置并直接返回。

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=9Output: index1=1, index2=2

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
map<int, int> table;
map<int, int>::iterator iter;
vector<int> result;
int comp;
for (int i = 0;i < numbers.size();++i) {
comp = target - numbers[i];
iter = table.find(comp);
if (iter == table.end()) {
table.insert(pair<int, int>(numbers[i], i));
} else {
result.push_back(iter->second + 1);
result.push_back(i + 1);
return result;
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode array hash table