Given an array of inergers, 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
方法一:
使用STL中定义的unorder_map将vector中元素的value 和 indice存入。遍历数组,找到两个相加是target的值。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> mapping;
vector<int> results;
for(int i = 0; i < numbers.size(); ++i)
{
mapping[numbers[i]] = i;
}
for(int i = 0; i < numbers.size(); ++i){
const int gap = target - numbers[i];
if(mapping.find(gap) != mapping.end() && mapping[gap] > i)
{
results.push_back(i+1);
results.push_back(mapping[gap]+1);
break;
}
}
return results;
}
};</pre><pre code_snippet_id="621500" snippet_file_name="blog_20150317_4_3955113" name="code" class="cpp"><pre name="code" class="cpp">class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int i, sum;
vector<int> results;
map<int, int> hmap;
for(i=0; i<numbers.size(); i++){
if(!hmap.count(numbers[i])){
hmap.insert(pair<int, int>(numbers[i], i));
}
if(hmap.count(target-numbers[i])){
int n=hmap[target-numbers[i]];
if(n<i){
results.push_back(n+1);
results.push_back(i+1);
//cout<<n+1<<", "<<i+1<<endl;
return results;
}
}
}
return results;
}
};class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> map_index;
vector<int> res;
for (int i = 0; i < nums.size(); i++)
{
int find_num = target - nums[i];
if (map_index.find(find_num) != map_index.end())
{
res.push_back(map_index[find_num]);
res.push_back(i);
break;
}
map_index[nums[i]] = i;
}
return res;
}
};
本文介绍了一种方法,用于在给定数组中找到两个数,它们的和等于指定的目标值,并返回这两个数的索引。
819

被折叠的 条评论
为什么被折叠?



