Skip to content

Commit d38122f

Browse files
committed
New Problem "Two Sum III - Data structure design"
1 parent 5d6429d commit d38122f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/twoSum/twoSum.III.cpp

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Source : https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/
2+
// Author : Hao Chen
3+
// Date : 2014-12-29
4+
5+
/**********************************************************************************
6+
*
7+
* Design and implement a TwoSum class. It should support the following operations: add and find.
8+
*
9+
* add - Add the number to an internal data structure.
10+
* find - Find if there exists any pair of numbers which sum is equal to the value.
11+
*
12+
* For example,
13+
*
14+
* add(1); add(3); add(5);
15+
* find(4) -> true
16+
* find(7) -> false
17+
*
18+
**********************************************************************************/
19+
20+
class TwoSum {
21+
private:
22+
unordered_map<int, int> nums;
23+
public:
24+
25+
//O(1) add
26+
void add(int number) {
27+
nums[number]++;
28+
}
29+
30+
//O(n) find
31+
bool find(int value) {
32+
int one, two;
33+
for(auto it = nums.begin(); it != nums.end(); it++){
34+
one = it->first;
35+
two = value - one;
36+
if ( (one == two && it->second > 1) ||
37+
(one != two && nums.find(two) != nums.end() ) ){
38+
return true;
39+
}
40+
}
41+
return false;
42+
}
43+
};

0 commit comments

Comments
 (0)