File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change @@ -265,6 +265,7 @@ Problem | Solution | Time | Space | Difficul
265
265
[ Minimum Window Substring] | [ minimum-window-substring.py] | _ O(n^2)_ | _ O(n)_ | Hard |
266
266
[ Substring with Concatenation of All Words] | [ substring-with-concatenation-of-all-words.py] | _ O(m * n * k)_ | _ O(n * k)_ | Hard |
267
267
[ 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 |
268
269
[ Valid Sudoku] | [ valid-sudoku.py] | _ O(n)_ | _ O(n)_ | Easy |
269
270
270
271
[ 4 Sum ] : https://oj.leetcode.com/problems/4sum/
@@ -281,6 +282,8 @@ Problem | Solution | Time | Space | Difficul
281
282
[ substring-with-concatenation-of-all-words.py ] :https://github.com/kamyu104/LeetCode/blob/master/Python/substring-with-concatenation-of-all-words.py
282
283
[ Two Sum ] :https://oj.leetcode.com/problems/two-sum/
283
284
[ 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
284
287
[ Valid Sudoku ] :https://oj.leetcode.com/problems/valid-sudoku/
285
288
[ valid-sudoku.py ] :https://github.com/kamyu104/LeetCode/blob/master/Python/valid-sudoku.py
286
289
You can’t perform that action at this time.
0 commit comments