|
40 | 40 |
|
41 | 41 | ## Solutions
|
42 | 42 |
|
| 43 | +**Approach 1: Two Pointers** |
| 44 | + |
| 45 | +Time complexity $O(n^3)$, Space complexity $O(\log n)$. |
| 46 | + |
43 | 47 | <!-- tabs:start -->
|
44 | 48 |
|
45 | 49 | ### **Python3**
|
@@ -159,40 +163,35 @@ public:
|
159 | 163 |
|
160 | 164 | ```go
|
161 | 165 | func fourSum(nums []int, target int) [][]int {
|
162 |
| - n, res := len(nums), make([][]int, 0) |
163 |
| - if n < 4 { |
164 |
| - return res |
165 |
| - } |
| 166 | + ans, n := [][]int{}, len(nums) |
166 | 167 | sort.Ints(nums)
|
167 |
| - for i := 0; i < n-3; i++ { |
168 |
| - if i > 0 && nums[i] == nums[i-1] { |
169 |
| - continue |
170 |
| - } |
171 |
| - for j := i + 1; j < n-2; j++ { |
172 |
| - if j > i+1 && nums[j] == nums[j-1] { |
173 |
| - continue |
174 |
| - } |
175 |
| - k, l := j+1, n-1 |
176 |
| - for k < l { |
177 |
| - if nums[i]+nums[j]+nums[k]+nums[l] == target { |
178 |
| - res = append(res, []int{nums[i], nums[j], nums[k], nums[l]}) |
179 |
| - k++ |
180 |
| - l-- |
181 |
| - for k < n && nums[k] == nums[k-1] { |
182 |
| - k++ |
| 168 | + for i := 0; i < n; i++ { |
| 169 | + for j := i + 1; j < n; j++ { |
| 170 | + for l, r := j+1, n-1; l < r; { |
| 171 | + if nums[i]+nums[j]+nums[l]+nums[r] == target { |
| 172 | + ans = append(ans, []int{nums[i], nums[j], nums[l], nums[r]}) |
| 173 | + l, r = l+1, r-1 |
| 174 | + for l < r && nums[l] == nums[l-1] { |
| 175 | + l++ |
183 | 176 | }
|
184 |
| - for l > j && nums[l] == nums[l+1] { |
185 |
| - l-- |
| 177 | + for l < r && nums[r] == nums[r+1] { |
| 178 | + r-- |
186 | 179 | }
|
187 |
| - } else if nums[i]+nums[j]+nums[k]+nums[l] < target { |
188 |
| - k++ |
| 180 | + } else if nums[i]+nums[j]+nums[l]+nums[r] < target { |
| 181 | + l++ |
189 | 182 | } else {
|
190 |
| - l-- |
| 183 | + r-- |
191 | 184 | }
|
192 | 185 | }
|
| 186 | + for j+1 < n && nums[j+1] == nums[j] { |
| 187 | + j++ |
| 188 | + } |
| 189 | + } |
| 190 | + for i+1 < n && nums[i+1] == nums[i] { |
| 191 | + i++ |
193 | 192 | }
|
194 | 193 | }
|
195 |
| - return res |
| 194 | + return ans |
196 | 195 | }
|
197 | 196 | ```
|
198 | 197 |
|
|
0 commit comments