Skip to content

Commit df0b758

Browse files
committed
update
1 parent 3cb8ba4 commit df0b758

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
#
4+
# Design and implement a TwoSum class. It should support the following operations: add and find.
5+
#
6+
# add - Add the number to an internal data structure.
7+
# find - Find if there exists any pair of numbers which sum is equal to the value.
8+
#
9+
# For example,
10+
# add(1); add(3); add(5);
11+
# find(4) -> true
12+
# find(7) -> false
13+
#
14+
15+
class TwoSum:
16+
17+
# initialize your data structure here
18+
def __init__(self):
19+
self.lookup = {}
20+
21+
22+
# @return nothing
23+
def add(self, number):
24+
if number in self.lookup:
25+
self.lookup[number] += 1
26+
else:
27+
self.lookup[number] = 1
28+
29+
# @param value, an integer
30+
# @return a Boolean
31+
def find(self, value):
32+
for key in self.lookup:
33+
num = value - key
34+
if num in self.lookup and (num != key or self.lookup[key] > 1):
35+
return True
36+
return False
37+
38+
if __name__ == "__main__":
39+
Sol = TwoSum()
40+
for i in (1, 3, 5):
41+
Sol.add(i)
42+
for i in (4, 7):
43+
print Sol.find(i)
44+
45+

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ Problem | Solution | Time | Space | Difficul
265265
[Minimum Window Substring] | [minimum-window-substring.py] | _O(n^2)_ | _O(n)_ | Hard |
266266
[Substring with Concatenation of All Words] | [substring-with-concatenation-of-all-words.py] | _O(m * n * k)_ | _O(n * k)_ | Hard |
267267
[Two Sum] | [two-sum.py] | _O(n)_ | _O(n)_ | Medium |
268+
[Two Sum III - Data structure design] | [two-sum-iii-data-structure-design.py] | _O(n)_ | _O(n)_ | Easy |
268269
[Valid Sudoku] | [valid-sudoku.py] | _O(n)_ | _O(n)_ | Easy |
269270

270271
[4 Sum]: https://oj.leetcode.com/problems/4sum/
@@ -281,6 +282,8 @@ Problem | Solution | Time | Space | Difficul
281282
[substring-with-concatenation-of-all-words.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/substring-with-concatenation-of-all-words.py
282283
[Two Sum]:https://oj.leetcode.com/problems/two-sum/
283284
[two-sum.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum.py
285+
[Two Sum III - Data structure design]:https://oj.leetcode.com/problems/two-sum-iii-data-structure-design/
286+
[two-sum-iii-data-structure-design.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/two-sum-iii-data-structure-design.py
284287
[Valid Sudoku]:https://oj.leetcode.com/problems/valid-sudoku/
285288
[valid-sudoku.py]:https://github.com/kamyu104/LeetCode/blob/master/Python/valid-sudoku.py
286289

0 commit comments

Comments
 (0)