-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution001.cpp
More file actions
45 lines (42 loc) · 832 Bytes
/
solution001.cpp
File metadata and controls
45 lines (42 loc) · 832 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @file Leetcode: Two sum.
*
* @author cpselvis ([email protected])
* @date 2016.7.4
*/
#include<cstdio>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> output(2);
unordered_map<int, int> umap;
for (int i = 0, size = nums.size(); i < size; i ++)
{
if (umap.find(target - nums[i]) != umap.end())
{
output[0] = umap[target - nums[i]];
output[1] = i;
}
else
{
umap.insert(make_pair(nums[i], i));
}
}
return output;
}
};
// test
int main(int argc, char **argv)
{
Solution s;
int arr[] = {2, 7, 11, 15};
int target = 13;
vector<int> nums(arr, arr + 3);
vector<int> output = s.twoSum(nums, target);
printf("%d %d\n", output[0], output[1]);
}