forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
50 lines (39 loc) · 1.16 KB
/
main2.cpp
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
46
47
48
49
50
/// Source : https://leetcode.com/problems/two-sum/description/
/// Author : liuyubobobo
/// Time : 2017-11-15
#include <iostream>
#include <vector>
#include <cassert>
#include <unordered_map>
using namespace std;
/// Two-Pass Hash Table
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> record;
for(int i = 0 ; i < nums.size() ; i ++)
record[nums[i]] = i;
for(int i = 0 ; i < nums.size() ; i ++){
unordered_map<int,int>::iterator iter = record.find(target - nums[i]);
if(iter != record.end() && iter->second != i){
int res[] = {i, iter->second};
return vector<int>(res, res + 2);
}
}
throw invalid_argument("the input has no solution");
}
};
void printVec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
const int nums[] = {0,4,3,0};
vector<int> nums_vec( nums, nums + sizeof(nums)/sizeof(int) );
int target = 0;
printVec(Solution().twoSum(nums_vec, target));
return 0;
}