1
- # Time: O(n^2 * p )
2
- # Space: O(n^2 * p )
3
- #
1
+ # Time: O(n^3 )
2
+ # Space: O(1 )
3
+
4
4
# Given an array S of n integers,
5
5
# are there elements a, b, c, and d in S such that a + b + c + d = target?
6
6
# Find all unique quadruplets in the array which gives the sum of target.
16
16
# (-2, 0, 0, 2)
17
17
#
18
18
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 ):
21
21
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
+ """
22
63
nums , result , lookup = sorted (nums ), [], collections .defaultdict (list )
23
64
for i in xrange (0 , len (nums ) - 1 ):
24
65
for j in xrange (i + 1 , len (nums )):
@@ -42,11 +83,16 @@ def fourSum(self, nums, target):
42
83
result .append (quad )
43
84
return result
44
85
86
+
45
87
# Time: O(n^2 * p) ~ O(n^4)
46
88
# Space: O(n^2)
47
- class Solution2 :
48
- # @return a list of lists of length 4, [[val1,val2,val3,val4]]
89
+ class Solution3 (object ):
49
90
def fourSum (self , nums , target ):
91
+ """
92
+ :type nums: List[int]
93
+ :type target: int
94
+ :rtype: List[List[int]]
95
+ """
50
96
nums , result , lookup = sorted (nums ), [], collections .defaultdict (list )
51
97
for i in xrange (0 , len (nums ) - 1 ):
52
98
for j in xrange (i + 1 , len (nums )):
@@ -63,6 +109,7 @@ def fourSum(self, nums, target):
63
109
result .append (quad )
64
110
return sorted (result )
65
111
112
+
66
113
if __name__ == '__main__' :
67
114
result = Solution ().fourSum ([1 , 0 , - 1 , 0 , - 2 , 2 ], 0 )
68
115
print result
0 commit comments