1.two sum
问题追踪
error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
error This file requires compiler and library support for the \
- 查看g++编译器的版本
- 4.8以上版本支持C++ 11标准
- 配置文件写完后,source 命令可以立即刷新命令,而不用重新开机
- 配置文件选择为~/.bashrc,然后在该文件下添加如下的命令
unordered_map - C++ Reference(英)
unsordered_map的具体用法
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map> //C++ 11 standard
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> umap;
// initialize the variable with 0 to prevent none result
vector<int> output(2); // vector 2 data ,default data
for (int i = 0; i < numbers.size(); i++)
{
// Avoid the situations like 4 = 8 - 4
if (umap.find(numbers[i]) != umap.end())
{
output[0] = umap[numbers[i]] + 1;
output[1] = i + 1;
}
else
{
umap.insert(make_pair(target - numbers[i], i));
}
}
return output;
}
};
int main()
{
Solution s1;
vector<int> numbers = {1,2,4,4,5};
int target = 9;
vector<int> output = s1.twoSum(numbers, target);
cout << output[0] << " " << output[1] << endl;
return 0;
}