@@ -102,3 +102,104 @@ def twoSum(target, nums):
102102
103103 return res
104104 """
105+
106+
107+
108+ #2021/7/5
109+ """
110+ Hash Table
111+ Time: O(N^2)
112+ Space: O(N)
113+
114+ memo := {num:[index1, index2,...]}
115+ Iterate through every i and j, see if the required number exist in memo.
116+ """
117+ import collections
118+ class Solution (object ):
119+ def threeSum (self , nums ):
120+ memo = collections .defaultdict (list )
121+ N = len (nums )
122+ ans = set ()
123+
124+ for k in xrange (N ):
125+ memo [nums [k ]].append (k )
126+
127+ for i in xrange (N ):
128+ for j in xrange (i + 1 , N ):
129+ t = (nums [i ]+ nums [j ])* - 1
130+
131+ for k in memo [t ]:
132+ if k != i and k != j :
133+ ans .add (tuple (sorted ([nums [i ], nums [j ], nums [k ]])))
134+ break
135+ return ans
136+
137+ """
138+ Two Pointers
139+ Time: O(N^2)
140+ Space: O(1)
141+
142+ Sort the nums.
143+ Iterate through i.
144+ j = i+1 and k = N-1, see if the sum s equals to 0.
145+ if s>0, means that we need to reduce the s and it can only be done by decreasing k.
146+ if s<0, means that we need to increase the s and it can only be done by increasing j.
147+ """
148+ class Solution (object ):
149+ def threeSum (self , nums ):
150+ nums .sort ()
151+ ans = set ()
152+ N = len (nums )
153+
154+ for i in xrange (N ):
155+ j = i + 1
156+ k = N - 1
157+
158+ while j < k :
159+ s = nums [i ]+ nums [j ]+ nums [k ]
160+ if s > 0 :
161+ k -= 1
162+ elif s < 0 :
163+ j += 1
164+ else :
165+ ans .add (tuple (sorted ([nums [i ], nums [j ], nums [k ]])))
166+ k -= 1
167+ j += 1
168+
169+ return ans
170+
171+ """
172+ Two Pointers
173+ Time: O(N^2)
174+ Space: O(1)
175+
176+ Same as above. Move pointers to avoid repeation. Faster.
177+ """
178+ class Solution (object ):
179+ def threeSum (self , nums ):
180+ nums .sort ()
181+ ans = []
182+ N = len (nums )
183+
184+ for i in xrange (N ):
185+ j = i + 1
186+ k = N - 1
187+
188+ if i > 0 and nums [i ]== nums [i - 1 ]: continue #[1]
189+
190+ while j < k :
191+ s = nums [i ]+ nums [j ]+ nums [k ]
192+
193+ if s > 0 :
194+ k -= 1
195+ elif s < 0 :
196+ j += 1
197+ else :
198+ ans .append ([nums [i ], nums [j ], nums [k ]])
199+
200+ while j < k and nums [k ]== nums [k - 1 ]: k -= 1 #[2]
201+ while j < k and nums [j ]== nums [j + 1 ]: j += 1 #[3]
202+ k -= 1
203+ j += 1
204+
205+ return ans
0 commit comments