您的位置:首页 > 其它

leetCode#18. 4Sum

2018-01-09 14:15 197 查看

Description

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]


Code

class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in xrange(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for l in xrange(i + 1, len(nums) - 2):
if l > i + 1 and nums[l] == nums[l - 1]:
continue
m, r = l + 1, len(nums) - 1
while m < r:
s = nums[i] + nums[l] + nums[m] + nums[r]
if s < target:
m += 1
elif s > target:
r -= 1
else:
res.append((nums[i], nums[l], nums[m], nums[r]))
while m < r and nums[m] == nums[m + 1]:
m += 1
while m < r and nums[r] == nums[r - 1]:
r -= 1
m += 1; r -= 1
return res


Conclusion

这道题也是3sum的衍生题,在3sum的基础上多了一层循环。下面是另一种有意思且快速的解法:

Code(rikimberly)

public List<List<Integer>> fourSum(int[] nums, int target) {
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
int len = nums.length;
if (nums == null || len < 4)
return res;

Arrays.sort(nums);

int max = nums[len - 1];
if (4 * nums[0] > target || 4 * max < target)
return res;

int i, z;
for (i = 0; i < len; i++) {
z = nums[i];
if (i > 0 && z == nums[i - 1])// avoid duplicate
continue;
if (z + 3 * max < target) // z is too small
continue;
if (4 * z > target) // z is too large
break;
if (4 * z == target) { // z is the boundary
if (i + 3 < len && nums[i + 3] == z)
res.add(Arrays.asList(z, z, z, z));
break;
}

threeSumForFourSum(nums, target - z, i + 1, len - 1, res, z);
}

return res;
}

/*
* Find all possible distinguished three numbers adding up to the target
* in sorted array nums[] between indices low and high. If there are,
* add all of them into the ArrayList fourSumList, using
* fourSumList.add(Arrays.asList(z1, the three numbers))
*/
public void threeSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,
int z1) {
if (low + 1 >= high)
return;

int max = nums[high];
if (3 * nums[low] > target || 3 * max < target)
return;

int i, z;
for (i = low; i < high - 1; i++) {
z = nums[i];
if (i > low && z == nums[i - 1]) // avoid duplicate
continue;
if (z + 2 * max < target) // z is too small
continue;

if (3 * z > target) // z is too large
break;

if (3 * z == target) { // z is the boundary
if (i + 1 < high && nums[i + 2] == z)
fourSumList.add(Arrays.asList(z1, z, z, z));
break;
}

twoSumForFourSum(nums, target - z, i + 1, high, fourSumList, z1, z);
}

}

/*
* Find all possible distinguished two numbers adding up to the target
* in sorted array nums[] between indices low and high. If there are,
* add all of them into the ArrayList fourSumList, using
* fourSumList.add(Arrays.asList(z1, z2, the two numbers))
*/
public void twoSumForFourSum(int[] nums, int target, int low, int high, ArrayList<List<Integer>> fourSumList,
int z1, int z2) {

if (low >= high)
return;

if (2 * nums[low] > target || 2 * nums[high] < target)
return;

int i = low, j = high, sum, x;
while (i < j) {
sum = nums[i] + nums[j];
if (sum == target) {
fourSumList.add(Arrays.asList(z1, z2, nums[i], nums[j]));

x = nums[i];
while (++i < j && x == nums[i]) // avoid duplicate
;
x = nums[j];
while (i < --j && x == nums[j]) // avoid duplicate
;
}
if (sum < target)
i++;
if (sum > target)
j--;
}
return;
}


该算法虽然不简洁,但是效率很高,能够很快的从不满足条件的循环中跳出来,的确是另一种解题思路,将不满足的数据筛出来。

除此之外,评论区里还总结除了k sum的代码,如下:

Code(zhuyinghua1203)

def fourSum(self, nums, target):
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results

def findNsum(self, nums, target, N, result, results):
if len(nums) < N or N < 2: return

# solve 2-sum
if N == 2:
l,r = 0,len(nums)-1
while l < r:
if nums[l] + nums[r] == target:
results.append(result + [nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while r > l and nums[r] == nums[r + 1]:
r -= 1
elif nums[l] + nums[r] < target:
l += 1
else:
r -= 1
else:
for i in range(0, len(nums)-N+1):   # careful about range
if target < nums[i]*N or target > nums[-1]*N:  # take advantages of sorted list
break
if i == 0 or i > 0 and nums[i-1] != nums[i]:  # recursively reduce N
self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)
return


Conclusion

至此,k sum的题告一段落了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: