描述

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.

示例

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]
]

算法分析

难度:中

分析:给定整型数组和指定一个整型目标值,从整形数组中找出4个不同的元素,使得4个元素之和等于目标值,返回结果为所有满足上述条件的元素组合。

思路:思路可以参考3Sum,主要难度是由原先的找3个元素之和,变成了找4个元素之和。这种情况下,其实有点像解魔方:玩五阶魔方就是从五阶降到四阶,然后再从四阶降到三阶,最后再按照玩三阶魔方的方法解决问题。

最终的解法,其实就是在3阶解法的基础上,在外层再套一层4阶的循环,并做一些基础的判断,复杂度也是在3阶n²基础上*n=n³,当然,这种算法也可推广到n阶。

代码示例(C#)

public IList<IList<int>> FourSum(int[] nums, int target)
{
List<IList<int>> res = new List<IList<int>>();
if (nums.Length < 4) return res; //排序
Array.Sort(nums);
//4阶判断
for (int i = 0; i < nums.Length - 3; i++)
{
//如果最近4个元素之和都大于目标值,因为数组是排序的,后续只可能更大,所以跳出循环
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
//当前元素和最后3个元素之和小于目标值即本轮最大值都小于目标值,则本轮不满足条件,跳过本轮
if (nums[i] + nums[nums.Length - 1] + nums[nums.Length - 2] + nums[nums.Length - 3] < target)
continue;
//防止重复组合
if (i > 0 && nums[i] == nums[i - 1]) continue; //3阶判断
for (int j = i + 1; j < nums.Length - 2; j++)
{
//原理同4阶判断
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
if (nums[i] + nums[j] + nums[nums.Length - 1] + nums[nums.Length - 2] < target)
continue; int lo = j + 1, hi = nums.Length - 1;
while (lo < hi)
{
//已知元素 nums[i],nums[j],剩下2个元素做夹逼
int sum = nums[i] + nums[j] + nums[lo] + nums[hi];
if (sum == target)
{
res.Add(new List<int> { nums[i], nums[j], nums[lo], nums[hi] });
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
lo++;
hi--;
}
//两边夹逼
else if (sum < target) lo++;
else hi--;
}
}
}
return res;
}

复杂度

  • 时间复杂度O (n³).
  • 空间复杂度O (1).

附录

算法题丨4Sum的更多相关文章

  1. 算法题丨Two Sum

    描述 Given an array of integers, return indices of the two numbers such that they add up to a specific ...

  2. 算法题丨3Sum

    描述 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...

  3. 算法题丨3Sum Closest

    描述 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...

  4. 算法题丨Remove Duplicates from Sorted Array II

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 示例 Giv ...

  5. 算法题丨Longest Consecutive Sequence

    描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence ...

  6. 算法题丨Remove Element

    描述 Given an array and a value, remove all instances of that value in-place and return the new length ...

  7. 算法题丨Move Zeroes

    描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the rela ...

  8. 算法题丨Next Permutation

    描述 Implement next permutation, which rearranges numbers into the lexicographically next greater perm ...

  9. 算法题丨Remove Duplicates from Sorted Array

    描述 Given a sorted array, remove the duplicates in-place such that each element appear only once and ...

随机推荐

  1. assert断言检测

    assert 是宏,非函数,包含在assert.h 头文件中. 如果其后面括号里的值为假,则程序终止运行,并提示出错.这个 宏只在 Debug 版本上起作用,而在 Release 版本被编译器完全优化 ...

  2. 关于win8/win8.1系统不能调节亮度的解决办法

    有时候我们重装了win8系统之后开始可以调节亮度,但是再重新安装了显卡驱动之后发现不能调节亮度了,解决办法就是添加一项注册表. 下载地址:http://7xnarc.com1.z0.glb.cloud ...

  3. Python 从入门到入门基础练习十五题

    **a) 6.成绩转换:编写一个学生成绩转换程序,用户输入百分制的学生成绩,成绩大于或等于60的输出"pass",否则输出"fail",成绩不四舍五入. a = ...

  4. jquery ajax 返回的json对象 新增属性值(干货)

    $.ajax({ type:"GEt'; url:"你的地址", data:{"你的字段","字段值"} success:funt ...

  5. 用disabled属性修饰a标签,a标签仍然能点击

    1.不知道各位同学有没有遇到跟我相同的问题,就是用jQuery操作a标签disabled的,来控制重复提交表单 做过开发的都知道,表单验证重复提交,包含前端和后端,两方面的控制.前端控制使我们常用的手 ...

  6. 微信扫一扫JSSDK 扫一扫报错 invalid signature 问题

    交代一下业务场景 在在四个页面都需要用到扫一扫去扫二维码.然而在图三-我的订单 下单中这个页面扫一扫不起效,当时就郁闷了为啥其他页面有用,这里却没用,开始调试吧. 报错信息是签名验证不成功. 自己去打 ...

  7. spring boot高性能实现二维码扫码登录(上)——单服务器版

    前言 目前网页的主流登录方式是通过手机扫码二维码登录.我看了网上很多关于扫码登录博客后,发现基本思路大致是:打开网页,生成uuid,然后长连接请求后端并等待登录认证相应结果,而后端每个几百毫秒会循环查 ...

  8. poj supermaket (贪心)

    http://poj.org/problem?id=1456 #include<cstring> #include<iostream> #include<algorith ...

  9. Oracle查询优化改写--------------------范围处理

    一.定位连续值的范围 二.查找同一组或分区中行之间的差

  10. curl的使用基本流程,HTTP的get请求,post请求

    使用CURL的PHP扩展完成一个HTTP请求的发送一般有以下几个步骤: 1.初始化连接句柄: 2.设置CURL选项: 3.执行并获取结果: 4.释放VURL连接句柄. 下面的程序片段是使用CURL发送 ...