File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments