Skip to content

Commit 904ec53

Browse files
committed
Update 4sum.py
1 parent c874c14 commit 904ec53

File tree

1 file changed

+54
-7
lines changed

1 file changed

+54
-7
lines changed

Python/4sum.py

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# Time: O(n^2 * p)
2-
# Space: O(n^2 * p)
3-
#
1+
# Time: O(n^3)
2+
# Space: O(1)
3+
44
# Given an array S of n integers,
55
# are there elements a, b, c, and d in S such that a + b + c + d = target?
66
# Find all unique quadruplets in the array which gives the sum of target.
@@ -16,9 +16,50 @@
1616
# (-2, 0, 0, 2)
1717
#
1818

19-
class Solution:
20-
# @return a list of lists of length 4, [[val1,val2,val3,val4]]
19+
# Two pointer solution. (1356ms)
20+
class Solution(object):
2121
def fourSum(self, nums, target):
22+
"""
23+
:type nums: List[int]
24+
:type target: int
25+
:rtype: List[List[int]]
26+
"""
27+
nums.sort()
28+
res = []
29+
for i in xrange(len(nums) - 3):
30+
if i and nums[i] == nums[i - 1]:
31+
continue
32+
for j in xrange(i + 1, len(nums) - 2):
33+
if j != i + 1 and nums[j] == nums[j - 1]:
34+
continue
35+
sum = target - nums[i] - nums[j]
36+
left, right = j + 1, len(nums) - 1
37+
while left < right:
38+
if nums[left] + nums[right] == sum:
39+
res.append([nums[i], nums[j], nums[left], nums[right]])
40+
right -= 1
41+
left += 1
42+
while left < right and nums[left] == nums[left - 1]:
43+
left += 1
44+
while left < right and nums[right] == nums[right + 1]:
45+
right -= 1
46+
elif nums[left] + nums[right] > sum:
47+
right -= 1
48+
else:
49+
left += 1
50+
return res
51+
52+
53+
# Time: O(n^2 * p)
54+
# Space: O(n^2 * p)
55+
# Hash solution. (224ms)
56+
class Solution2(object):
57+
def fourSum(self, nums, target):
58+
"""
59+
:type nums: List[int]
60+
:type target: int
61+
:rtype: List[List[int]]
62+
"""
2263
nums, result, lookup = sorted(nums), [], collections.defaultdict(list)
2364
for i in xrange(0, len(nums) - 1):
2465
for j in xrange(i + 1, len(nums)):
@@ -42,11 +83,16 @@ def fourSum(self, nums, target):
4283
result.append(quad)
4384
return result
4485

86+
4587
# Time: O(n^2 * p) ~ O(n^4)
4688
# Space: O(n^2)
47-
class Solution2:
48-
# @return a list of lists of length 4, [[val1,val2,val3,val4]]
89+
class Solution3(object):
4990
def fourSum(self, nums, target):
91+
"""
92+
:type nums: List[int]
93+
:type target: int
94+
:rtype: List[List[int]]
95+
"""
5096
nums, result, lookup = sorted(nums), [], collections.defaultdict(list)
5197
for i in xrange(0, len(nums) - 1):
5298
for j in xrange(i + 1, len(nums)):
@@ -63,6 +109,7 @@ def fourSum(self, nums, target):
63109
result.append(quad)
64110
return sorted(result)
65111

112+
66113
if __name__ == '__main__':
67114
result = Solution().fourSum([1, 0, -1, 0, -2, 2], 0)
68115
print result

0 commit comments

Comments
 (0)