|
| 1 | +# -*- coding: utf-8 -*- |
1 | 2 | # Time Limit Exceeded
|
2 |
| -class Solution: |
3 |
| - # @return a list of lists of length 4, [[val1,val2,val3,val4]] |
4 |
| - def fourSum(self, num, target): |
5 |
| - n = len(num) |
6 |
| - num.sort() |
| 3 | +""" |
| 4 | +Given an array S of n integers, are there elements a, b, c, and d in S such |
| 5 | +that a + b + c + d = target? Find all unique quadruplets in the array which |
| 6 | +gives the sum of target. |
| 7 | +
|
| 8 | +Note: |
| 9 | +Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b |
| 10 | +≤ c ≤ d) |
| 11 | +The solution set must not contain duplicate quadruplets. |
| 12 | + For example, given array S = {1 0 -1 0 -2 2}, and target = 0. |
| 13 | +
|
| 14 | + A solution set is: |
| 15 | + (-1, 0, 0, 1) |
| 16 | + (-2, -1, 1, 2) |
| 17 | + (-2, 0, 0, 2) |
| 18 | +""" |
| 19 | + |
| 20 | + |
| 21 | +class Solution(object): |
| 22 | + def fourSum(self, nums, target): |
| 23 | + """ |
| 24 | + :type nums: List[int] |
| 25 | + :type target: int |
| 26 | + :rtype: List[List[int]] |
| 27 | + """ |
| 28 | + n = len(nums) |
| 29 | + nums.sort() |
7 | 30 | res = []
|
8 | 31 | for a in range(n - 3):
|
9 |
| - if a > 0 and num[a - 1] == num[a]: |
| 32 | + if a > 0 and nums[a - 1] == nums[a]: |
10 | 33 | continue
|
11 | 34 | for b in range(a + 1, n - 2):
|
12 |
| - if b > a + 1 and num[b - 1] == num[b]: |
| 35 | + if b > a + 1 and nums[b - 1] == nums[b]: |
13 | 36 | continue
|
14 | 37 | c = b + 1
|
15 | 38 | d = n - 1
|
16 | 39 | while c < d:
|
17 |
| - s = num[a] + num[b] + num[c] + num[d] |
| 40 | + s = nums[a] + nums[b] + nums[c] + nums[d] |
18 | 41 | if s == target:
|
19 |
| - res.append([num[a], num[b], num[c], num[d]]) |
| 42 | + res.append([nums[a], nums[b], nums[c], nums[d]]) |
20 | 43 | c += 1
|
21 | 44 | d -= 1
|
22 |
| - while c < d and num[c] == num[c - 1]: |
| 45 | + while c < d and nums[c] == nums[c - 1]: |
23 | 46 | c += 1
|
24 |
| - while c < d and num[d] == num[d + 1]: |
| 47 | + while c < d and nums[d] == nums[d + 1]: |
25 | 48 | d -= 1
|
26 | 49 | elif s < target:
|
27 | 50 | c += 1
|
|
0 commit comments