LeetCode:3Sum, 3Sum Closest, 4Sum
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
我们可以在 2sum问题 的基础上来解决3sum问题,假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。
我们以选第一个和第二个举例,假设数组为A[],总共有n个元素A1,A2....An。很显然,当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A3~An],目标位target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题。
对于本题要求的求最接近解,只需要保存当前解以及当前解和目标的距离,如果新的解更接近,则更新解。算法复杂度为O(n^2);
注意:我们这里是求的和是一个非确定性的数,因此2sum问题的hashtable解法就不适合这里了
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int n = num.size();
sort(num.begin(), num.end());
int res, dis = INT_MAX;
for(int i = ; i < n - ; i++)
{
int target2 = target - num[i], tmpdis;
int tmpres = twoSumClosest(num, i+, target2);
if((tmpdis = abs(tmpres - target2)) < dis)
{
res = tmpres + num[i];
dis = tmpdis;
if(res == target)
return res;
}
}
return res;
}
int twoSumClosest(vector<int> &sortedNum, int start, int target)
{
int head = start, tail = sortedNum.size() - ;
int res, dis = INT_MAX;
while(head < tail)
{
int tmp = sortedNum[head] + sortedNum[tail];
if(tmp < target)
{
if(target - tmp < dis)
{
res = tmp;
dis = target - tmp;
}
head++;
}
else if(tmp > target)
{
if(tmp - target < dis)
{
res = tmp;
dis = tmp - target;
}
tail--;
}
else
return target;
}
return res;
}
};
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets. 本文地址
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
为了避免重复,对于排序后的数组,当我们枚举第一个数时,如果遇到重复的就直接跳过;当我们找到一个符合的二元组(第二个数和第三个数)时,也分别对第二个数和第三个数去重。具体见代码注释。代码中的两个函数也可以合并成一个。
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
int n = num.size();
sort(num.begin(), num.end());
vector<vector<int> > res;
for(int i = ; i < n-; i++)
{
if(i > && num[i] == num[i-])continue;//重复的元素不用计算
int target2 = - num[i];
twoSum(num, i+, target2, res);
}
return res;
}
void twoSum(vector<int> &sortedNum, int start, int target, vector<vector<int> >&res)
{
int head = start, tail = sortedNum.size() - ;
while(head < tail)
{
int tmp = sortedNum[head] + sortedNum[tail];
if(tmp < target)
head++;
else if(tmp > target)
tail--;
else
{ ;
res.push_back(vector<int>{sortedNum[start-], sortedNum[head], sortedNum[tail]});
//为了防止出现重复的二元组,使结果等于target
int k = head+;
while(k < tail && sortedNum[k] == sortedNum[head])k++;
head = k;
k = tail-;
while(k > head && sortedNum[k] == sortedNum[tail])k--;
tail = k;
}
}
}
};
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
算法1:我们可以仿照3sum的解决方法。这里枚举第一个和第二个数,然后对余下数的求2sum,算法复杂度为O(n^3),去重方法和上一题类似
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int n = num.size();
vector<vector<int> > res;
sort(num.begin(), num.end());
for(int i = ; i < n-; i++)
{
if(i > && num[i] == num[i-])continue;//防止第一个元素重复
for(int j = i+; j < n-; j++)
{
if(j > i+ && num[j] == num[j-])continue;//防止第二个元素重复
int target2 = target - num[i] - num[j];
int head = j+, tail = n-;
while(head < tail)
{
int tmp = num[head] + num[tail];
if(tmp > target2)
tail--;
else if(tmp < target2)
head++;
else
{
res.push_back(vector<int>{num[i], num[j], num[head], num[tail]});
//为了防止出现重复的二元组,使结果等于target2
int k = head+;
while(k < tail && num[k] == num[head])k++;
head = k;
k = tail-;
while(k > head && num[k] == num[tail])k--;
tail = k;
}
}
}
}
return res;
}
};
算法2:O(n^2)的算法,和前面相当,都是先对数组排序。我们先枚举出所有二个数的和存放在哈希map中,其中map的key对应的是二个数的和,因为多对元素求和可能是相同的值,故哈希map的value是一个链表(下面的代码中用数组代替),链表每个节点存的是这两个数在数组的下标;这个预处理的时间复杂度是O(n^2)。接着和算法1类似,枚举第一个和第二个元素,假设分别为v1,v2, 然后在哈希map中查找和为target-v1-v2的所有二元对(在对应的链表中),查找的时间为O(1),为了保证不重复计算,我们只保留两个数下标都大于V2的二元对(其实我们在前面3sum问题中所求得的三个数在排序后的数组中下标都是递增的),即时是这样也有可能重复:比如排好序后数组为-9 -4 -2 0 2 4 4,target = 0,当第一个和第二个元素分别是-4,-2时,我们要得到和为0-(-2)-(-4) = 6的二元对,这样的二元对有两个,都是(2,4),且他们在数组中的下标都大于-4和-2,如果都加入结果,则(-4,-2,2,4)会出现两次,因此在加入二元对时,要判断是否和已经加入的二元对重复(由于过早二元对之前数组已经排过序,所以两个元素都相同的二元对可以保证在链表中是相邻的,链表不会出现(2,4)->(1,5)->(2,4)的情况,因此只要判断新加入的二元对和上一个加入的二元对是否重复即可),因为同一个链表中的二元对两个元素的和都是相同的,因此只要二元对的一个元素不同,则这个二元对就不同。我们可以认为哈希map中key对应的链表长度为常数,那么算法总的复杂度为O(n^2)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int n = num.size();
vector<vector<int> > res;
unordered_map<int, vector<pair<int, int> > >pairs;
pairs.reserve(n*n);
sort(num.begin(), num.end());
for(int i = ; i < n; i++)
for(int j = i+ ; j < n; j++)
pairs[num[i]+num[j]].push_back(make_pair(i,j));
for(int i = ; i < n - ; i++)
{
if(i != && num[i] == num[i-])continue;//防止第一个元素重复
for(int j = i+; j < n - ; j++)
{
if(j != i+ && num[j] == num[j-])continue;//防止第二个元素重复
if(pairs.find(target - num[i] - num[j]) != pairs.end())
{
vector<pair<int, int>> &sum2 = pairs[target - num[i] - num[j]];
bool isFirstPush = true;
for(int k = ; k < sum2.size(); k++)
{
if(sum2[k].first <= j)continue;//保证所求的四元组的数组下标是递增的
if(isFirstPush || (res.back())[] != num[sum2[k].first])
{
res.push_back(vector<int>{num[i], num[j], num[sum2[k].first], num[sum2[k].second]});
isFirstPush = false;
}
}
}
}
}
return res;
}
};
对于k-sum问题,我们可以不断的转化为k-1 sum, k-2 sum 直到2sum;也可以像4sum问题的hashmap解法一样,分成若干个2sum问题。可以参看这篇文章:
k sum problem (k 个数的求和问题)
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3649607.html
LeetCode:3Sum, 3Sum Closest, 4Sum的更多相关文章
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- [Leetcode][016] 3Sum Closest (Java)
题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...
- [LeetCode] 15. 3Sum 三数之和
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- [LeetCode] 259. 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
- LeetCode 15 3Sum [sort] <c++>
LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...
- LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum
1. Two Sum 题目链接 题目要求: Given an array of integers, find two numbers such that they add up to a specif ...
- LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum
n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...
- LeetCode (13): 3Sum Closest
https://leetcode.com/problems/3sum-closest/ [描述] Given an array S of n integers, find three integers ...
随机推荐
- Javaweb学习笔记——上传下载文件
一.前言 在Javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为comm ...
- jquery.zclip轻量级复制失效问题
工作原理 利用一个透明的 Flash ,让其漂浮在按钮之上,这样其实点击的不是按钮而是 Flash ,也就可以使用 Flash 的复制功能了 <script src="js/jquer ...
- JS高程3.基本概念(3)
1.ECMAScript数值的范围 由于内存的限制,在大多数浏览器中,ECMAScript能够拿保存的数据的范围是 5e-324 ~ 1.7976931348623157e+308,其中最小的数值保存 ...
- Android开发4: Notification编程基础、Broadcast的使用及其静态注册、动态注册方式
前言 啦啦啦~(博主每次开篇都要卖个萌,大家是不是都厌倦了呢~) 本篇博文希望帮助大家掌握 Broadcast 编程基础,实现动态注册 Broadcast 和静态注册 Broadcast 的方式以及学 ...
- 移动AD的计算机到对应的OU的powershell脚本
#//************************************************************* #//编辑人: #//编辑单位: #//编辑作用:移动计算机到对应的O ...
- UTF-8和GBK等中文字符编码格式介绍及相互转换
我们有很多时候需要使用中文编码格式,比如gbk.gb2312等,但是因为主要针对中文编码设置,因此并不完全通用,这样一来就有了在各编码间相互转换的需求,比如和UTF8的转换.可是在我使用的过程中,却发 ...
- iOS cocoapods升级及问题
安装 安装RubyCocoaPods基于Ruby语言开发而成,因此安装CocoaPods前需要安装Ruby环境.幸运的是Mac系统默认自带Ruby环境,如果没有请自行查找安装.检测是否安装Ruby:$ ...
- 从英文变形规则计算到Restful Api设计
➠更多技术干货请戳:听云博客 一天在研究Restful API设计,命名的时候我总是很纠结,我相信大多数人也有这种感觉,不是说想不出来某个单词怎么写的问题,像我这种没事背单词背到13000词量的人也要 ...
- Xcode出现( linker command failed with exit code 1)错误总结
这种问题,通常出现在添加第三方库文件或者多人开发时. 这种问题一般是找不到文件而导致的链接错误. 我们可以从如下几个方面着手排查. 先可以再试试一下几个方法: 1,看看是不是有新添加的文件跟之前文件 ...
- js 随机生成姓名、手机号、身份证号、银行卡号
开发测试的时候,经常需要填写姓名.手机号.身份证号.银行卡号,既要符合格式要求.又不能重复.大家会到网上搜各种生成器.能不能自己写一个简单的生成器呢.下面是随机生成姓名.手机号.身份证号.银行卡号的j ...