forked from yennanliu/CS_basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4sum.py
More file actions
448 lines (401 loc) · 15.1 KB
/
4sum.py
File metadata and controls
448 lines (401 loc) · 15.1 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
"""
18. 4Sum
Medium
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
Constraints:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
"""
# V0
class Solution(object):
def fourSum(self, nums, target):
resultList = []
nums.sort()
for num1 in range(0, len(nums)-3):
for num2 in range(num1 + 1, len(nums)-2):
num3 = num2 + 1
num4 = len(nums) -1
while num3 != num4:
summer = nums[num1] + nums[num2] + nums[num3] + nums[num4]
if summer == target:
list_temp = [nums[num1],nums[num2],nums[num3],nums[num4]]
if list_temp not in resultList:
resultList.append(list_temp)
num3 += 1
elif summer > target:
num4 -= 1
else:
num3 += 1
return resultList
# V1
# https://leetcode.com/problems/4sum/discuss/164105/Python-solution
# IDEA : BREAK DOWN + 2 SUM
# First sort the array, loop over the first two indices i & j, and the problem reduces to the 2Sum problem, i.e., finding two indices k & l such that nums[k]+nums[l] == target - nums[i] - nums[j], which takes O(N) time. The total time complexity is then O(N^3).
class Solution(object):
def fourSum(self, nums, target):
N = len(nums)
if N < 4:
return []
res = []
nums = sorted(nums)
i = 0
for i in range(N-3):
if 0 < i < N-3 and nums[i] == nums[i-1]:
continue
for j in range(i+1,N-2):
if i+1 < j < N-2 and nums[j] == nums[j-1]:
continue
k = j+1
l = N-1
while k < l:
summ = nums[i]+nums[j]+nums[k]+nums[l]
if summ == target:
res.append([nums[i],nums[j],nums[k],nums[l]])
while k < N-1 and nums[k] == nums[k+1]:
k += 1
while l > 0 and nums[l] == nums[l-1]:
l -= 1
k += 1
l -= 1
elif summ < target:
k += 1
else:
l -= 1
return res
# V1'
# https://leetcode.com/problems/4sum/solution/
# IDEA : HASH SET
class Solution:
def fourSum(self, nums, target):
def kSum(nums, target, k):
res = []
# If we have run out of numbers to add, return res.
if not nums:
return res
# There are k remaining values to add to the sum. The
# average of these values is at least target // k.
average_value = target // k
# We cannot obtain a sum of target if the smallest value
# in nums is greater than target // k or if the largest
# value in nums is smaller than target // k.
if average_value < nums[0] or nums[-1] < average_value:
return res
if k == 2:
return twoSum(nums, target)
for i in range(len(nums)):
if i == 0 or nums[i - 1] != nums[i]:
for subset in kSum(nums[i + 1:], target - nums[i], k - 1):
res.append([nums[i]] + subset)
return res
def twoSum(nums, target):
res = []
s = set()
for i in range(len(nums)):
if len(res) == 0 or res[-1][1] != nums[i]:
if target - nums[i] in s:
res.append([target - nums[i], nums[i]])
s.add(nums[i])
return res
nums.sort()
return kSum(nums, target, 4)
# V1''
# https://leetcode.com/problems/4sum/solution/
# IDEA : Two Pointers
class Solution:
def fourSum(self, nums, target):
def kSum(nums, target, k):
res = []
# If we have run out of numbers to add, return res.
if not nums:
return res
# There are k remaining values to add to the sum. The
# average of these values is at least target // k.
average_value = target // k
# We cannot obtain a sum of target if the smallest value
# in nums is greater than target // k or if the largest
# value in nums is smaller than target // k.
if average_value < nums[0] or nums[-1] < average_value:
return res
if k == 2:
return twoSum(nums, target)
for i in range(len(nums)):
if i == 0 or nums[i - 1] != nums[i]:
for subset in kSum(nums[i + 1:], target - nums[i], k - 1):
res.append([nums[i]] + subset)
return res
def twoSum(nums, target):
res = []
lo, hi = 0, len(nums) - 1
while (lo < hi):
curr_sum = nums[lo] + nums[hi]
if curr_sum < target or (lo > 0 and nums[lo] == nums[lo - 1]):
lo += 1
elif curr_sum > target or (hi < len(nums) - 1 and nums[hi] == nums[hi + 1]):
hi -= 1
else:
res.append([nums[lo], nums[hi]])
lo += 1
hi -= 1
return res
nums.sort()
return kSum(nums, target, 4)
# V1'''
# https://leetcode.com/problems/4sum/discuss/8604/Python-solution-with-detailed-explanation
# IDEA : BREAK DOWN + 3 SUM
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
N, result = len(nums), []
for i in range(N):
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, N):
if j > i+1 and nums[j] == nums[j-1]:
continue
x = target - nums[i] - nums[j]
s,e = j+1, N-1
while s < e:
if nums[s]+nums[e] == x:
result.append([nums[i], nums[j], nums[s], nums[e]])
s = s+1
while s < e and nums[s] == nums[s-1]:
s = s+1
elif nums[s]+nums[e] < x:
s = s+1
else:
e = e-1
return result
# V1'''''
# https://blog.csdn.net/qqxx6661/article/details/77104868
# IDEA : DOUBLE POINTER
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
resultList = []
nums.sort()
for num1 in range(0, len(nums)-3):
for num2 in range(num1 + 1, len(nums)-2):
num3 = num2 + 1
num4 = len(nums) -1
while num3 != num4:
summer = nums[num1] + nums[num2] + nums[num3] + nums[num4]
if summer == target:
list_temp = [nums[num1],nums[num2],nums[num3],nums[num4]]
if list_temp not in resultList:
resultList.append(list_temp)
num3 += 1
elif summer > target:
num4 -= 1
else:
num3 += 1
return resultList
# V1'''''
# https://blog.csdn.net/qqxx6661/article/details/77104868
# IDEA : DOUBLE POINTER + HASH TABLE
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
numLen, res, num_dict = len(nums), set(), {}
if numLen < 4:
return []
nums.sort()
for p in range(numLen): # save to hash table
for q in range(p+1, numLen):
if nums[p]+nums[q] not in num_dict:
num_dict[nums[p]+nums[q]] = [(p,q)]
else:
num_dict[nums[p]+nums[q]].append((p,q))
for i in range(numLen):
for j in range(i+1, numLen-2):
T = target-nums[i]-nums[j]
if T in num_dict:
for k in num_dict[T]:
if k[0] > j: res.add((nums[i],nums[j],nums[k[0]],nums[k[1]]))
return [list(i) for i in res]
# V1''''''
# https://blog.csdn.net/fuxuemingzhu/article/details/83543296
# IDEA : K SUM
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
N = len(nums)
nums.sort()
res = []
i = 0
while i < N - 3:
j = i + 1
while j < N - 2:
k = j + 1
l = N - 1
remain = target - nums[i] - nums[j]
while k < l:
if nums[k] + nums[l] > remain:
l -= 1
elif nums[k] + nums[l] < remain:
k += 1
else:
res.append([nums[i], nums[j], nums[k], nums[l]])
while k < l and nums[k] == nums[k + 1]:
k += 1
while k < l and nums[l] == nums[l - 1]:
l -= 1
k += 1
l -= 1
while j < N - 2 and nums[j] == nums[j + 1]:
j += 1
j += 1 # check this
while i < N - 3 and nums[i] == nums[i + 1]:
i += 1
i += 1 # check this
return res
# V1''''''''
# https://www.jiuzhang.com/solution/4sum/#tag-highlight-lang-python
class Solution(object):
def fourSum(self, nums, target):
nums.sort()
res = []
length = len(nums)
for i in range(0, length - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, length - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
sum = target - nums[i] - nums[j]
left, right = j + 1, length - 1
while left < right:
if nums[left] + nums[right] == sum:
res.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
left += 1
return res
# V2
# Time: O(n^3)
# Space: O(1)
import collections
# Two pointer solution. (1356ms)
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
res = []
for i in range(len(nums) - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, len(nums) - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
sum = target - nums[i] - nums[j]
left, right = j + 1, len(nums) - 1
while left < right:
if nums[left] + nums[right] == sum:
res.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
left += 1
return res
# Time: O(n^2 * p)
# Space: O(n^2 * p)
# Hash solution. (224ms)
import collections
class Solution2(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums, result, lookup = sorted(nums), [], collections.defaultdict(list)
for i in range(0, len(nums) - 1):
for j in range(i + 1, len(nums)):
is_duplicated = False
for [x, y] in lookup[nums[i] + nums[j]]:
if nums[x] == nums[i]:
is_duplicated = True
break
if not is_duplicated:
lookup[nums[i] + nums[j]].append([i, j])
ans = {}
for c in range(2, len(nums)):
for d in range(c+1, len(nums)):
if target - nums[c] - nums[d] in lookup:
for [a, b] in lookup[target - nums[c] - nums[d]]:
if b < c:
quad = [nums[a], nums[b], nums[c], nums[d]]
quad_hash = " ".join(str(quad))
if quad_hash not in ans:
ans[quad_hash] = True
result.append(quad)
return result
# Time: O(n^2 * p) ~ O(n^4)
# Space: O(n^2)
import collections
class Solution3(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums, result, lookup = sorted(nums), [], collections.defaultdict(list)
for i in range(0, len(nums) - 1):
for j in range(i + 1, len(nums)):
lookup[nums[i] + nums[j]].append([i, j])
for i in lookup.keys():
if target - i in lookup:
for x in lookup[i]:
for y in lookup[target - i]:
[a, b], [c, d] = x, y
if a is not c and a is not d and \
b is not c and b is not d:
quad = sorted([nums[a], nums[b], nums[c], nums[d]])
if quad not in result:
result.append(quad)
return sorted(result)