forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
56 lines (42 loc) · 1.24 KB
/
main.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
51
52
53
54
55
56
/// Source : https://leetcode.com/problems/two-sum-iii-data-structure-design/
/// Author : liuyubobobo
/// Time : 2016-12-03
#include <iostream>
#include <unordered_map>
#include <cassert>
#include <stdexcept>
using namespace std;
/// Using HashMap
/// Time Complexity: add: O(1) , find: O(n)
/// Space Complexity: O(n)
class TwoSum {
private:
// The numbers store the number pair represent (number, count of the number)
unordered_map<int,int> numbers;
public:
// Add the number to an internal data structure.
void add(int number) {
numbers[number] += 1;
}
// Find if there exists any pair of numbers which sum is equal to the value.
bool find(int value) {
for( unordered_map<int,int>::iterator iter = numbers.begin() ; iter != numbers.end() ; iter ++ ){
int num = iter->first;
if( numbers.find(value - num) != numbers.end() ){
if( value - num == num && numbers[num] == 1 )
continue;
return true;
}
}
return false;
}
};
int main() {
TwoSum twoSum;
twoSum.add(1);
twoSum.add(3);
twoSum.add(5);
cout << twoSum.find(4) << endl;
cout << twoSum.find(7) << endl;
return 0;
}