-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwo Sum III - Data structure design.py
65 lines (52 loc) · 1.52 KB
/
Two Sum III - Data structure design.py
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
57
58
59
60
61
62
63
64
65
'''
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
Example 1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Example 2:
add(3); add(1); add(2);
find(3) -> true
find(6) -> false
'''
class TwoSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.num_count = {}
self.found = set([])
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
if number in self.num_count:
self.num_count[number] += 1
else:
self.num_count[number] = 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
if value in self.found:
return True
for k, v in self.num_count.iteritems():
if value - k in self.num_count:
if value - k == k:
if v > 1:
self.found.add(value)
return True
else:
self.found.add(value)
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)