算法题丨4Sum
描述
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的更多相关文章
- 算法题丨Two Sum
描述 Given an array of integers, return indices of the two numbers such that they add up to a specific ...
- 算法题丨3Sum
描述 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...
- 算法题丨3Sum Closest
描述 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...
- 算法题丨Remove Duplicates from Sorted Array II
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 示例 Giv ...
- 算法题丨Longest Consecutive Sequence
描述 Given an unsorted array of integers, find the length of the longest consecutive elements sequence ...
- 算法题丨Remove Element
描述 Given an array and a value, remove all instances of that value in-place and return the new length ...
- 算法题丨Move Zeroes
描述 Given an array nums, write a function to move all 0's to the end of it while maintaining the rela ...
- 算法题丨Next Permutation
描述 Implement next permutation, which rearranges numbers into the lexicographically next greater perm ...
- 算法题丨Remove Duplicates from Sorted Array
描述 Given a sorted array, remove the duplicates in-place such that each element appear only once and ...
随机推荐
- java web(转)
装载:http://www.oschina.net/question/12_52027 OSCHINA 软件库有一个分类——Web框架,该分类中包含多种编程语言的将近500个项目. Web框架是开发者 ...
- MongoDB系列一(查询).
一.简述 MongoDB中使用find来进行查询.查询就是返回一个集合中文档的子集,子集合的范围从0个文档到整个集合.默认情况下,"_id"这个键总是被返回,即便是没有指定要返回这 ...
- 原生js获取left值和top值
在用js做动态效果时,通常需要获取元素绝对定位中的left和top属性值.比如做一个碰撞广告,就要不停的获取元素的top和left属性值. 需要注意的事:取值的元素必须要设置position:abso ...
- 关于Eclipse中Ctrl+Alt+Down和Ctrl+Alt+Up不起作用的解决方法
1.其它软件热键冲突,把其它软件的热键修改为其它按键,或者删掉热键 2.Intel显卡快捷键问题 1).你虽然禁用Intel快捷键,但是Intel快捷键仍然是Ctrl+alt+down,还是存在冲突, ...
- springMvc(一)
SpringMvc 1. 核心:DispatcherServlet 1.1作用:负责拦截请求并分派给相应的处理器处理 1.2配置DispatcherServlet(web.xml) 2.配置处理器映射 ...
- 关于数据库的左,右,内,外连接,Union和Union all---------笔记
1.左连接 select a.filed1,a.filed2,b.filed1 from a (左表) left join b(右表) on a.commonfiled = b.commonfiled ...
- Ajax教程(转载)
第 1 页 Ajax 简介Ajax 由 HTML.JavaScript™ 技术.DHTML 和 DOM 组成,这一杰出的方法可以将笨拙的 Web 界面转化成交互性的 Ajax 应用程序.本文的作者是一 ...
- 蓝牙4.0模块控制LED彩灯调光调色经验之谈
基于蓝牙模块的智能LED彩灯调光调色控制思路如下: 在此,找一个低功耗蓝牙模块内嵌接入LED灯的控制电路板,接入LED彩灯的控制电路中. 蓝牙模块彩灯控制方式如下,本文两类来解说led灯的控制方式: ...
- [poj3904]Sky Code_状态压缩_容斥原理
Sky Code poj-3904 题目大意:给你n个数,问能选出多少满足题意的组数. 注释:如果一个组数满足题意当且仅当这个组中有且只有4个数,且这4个数的最大公约数是1,$1\le n\le 10 ...
- 解决Hash碰撞冲突方法总结
Hash碰撞冲突 我们知道,对象Hash的前提是实现equals()和hashCode()两个方法,那么HashCode()的作用就是保证对象返回唯一hash值,但当两个对象计算值一样时,这就发生了碰 ...