8000 Two Sum III · leetcoders/LeetCode@05a7621 · GitHub
[go: up one dir, main page]

Skip to content

Commit 05a7621

Browse files
author
applewjg
committed
Two Sum III
Change-Id: I0c4829d45ac588f550939e13de9bda5af7819fec
1 parent ec0065f commit 05a7621

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

TwoSumIII.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 26, 2014
4+
Problem: Two Sum III - Data structure design
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/
7+
Notes:
8+
Design and implement a TwoSum class.
9+
It should support the following operations: add and find.
10+
add - Add the number to an internal data structure.
11+
find - Find if there exists any pair of numbers which sum is equal to the value.
12+
For example
13+
add(1); add(3); add(5);find(4) -> true; find(7) -> false,
14+
Solution: Thanks to Javaman Cao.
15+
*/
16+
17+
class TwoSum {
18+
public:
19+
unordered_map<int,int> hash;
20+
void add(int number) {
21+
++hash[number];
22+
}
23+
bool find(int value) {
24+
for (unordered_map<int,int>::iterator t = hash.begin(); t != hash.end(); ++t) {
25+
int x = value - t->first;
26+
if (x <= t->first) {
27+
unordered_map<int,int>::iterator it = hash.find(x);
28+
if ((it != hash.end()) && ((t != it) || (it->second > 1))) {
29+
return true;
30+
}
31+
}
32+
}
33+
return false;
34+
}
35+
};

0 commit comments

Comments
 (0)
0