3Sum Closest

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;
}
};

3Sum

Given an array S of n integers, are there elements abc 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;
}
}
}
};

4Sum

Given an array S of n integers, are there elements abc, 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的更多相关文章

  1. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  2. LeetCode 16. 3Sum Closest(最接近的三数之和)

    LeetCode 16. 3Sum Closest(最接近的三数之和)

  3. [Leetcode][016] 3Sum Closest (Java)

    题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...

  4. [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 ...

  5. [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 < ...

  6. LeetCode 15 3Sum [sort] <c++>

    LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...

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

  8. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  9. LeetCode (13): 3Sum Closest

    https://leetcode.com/problems/3sum-closest/ [描述] Given an array S of n integers, find three integers ...

随机推荐

  1. Bootstrap之字体图标

    优点:1.减少请求 2.容易控制样式 所在位置:在下载的bootstrap文件中的fonts文件夹存放字体图标 默认路径为当前目录下,如需修改路径,则需在bootstrap.css中查找font-fa ...

  2. MAC 如何使用Github Desktop 客户端

    作为开源代码库以及版本控制系统,Github拥有140多万开发者用户.随着越来越多的应用程序转移到了云上,Github已经成为了管理软件开发以及发现已有代码的首选方法.GitHub上已自动配置的Mac ...

  3. js获取网页高度

    网页可见区域宽: document.body.clientWidth网页可见区域高: document.body.clientHeight网页可见区域宽: document.body.offsetWi ...

  4. Android 手机卫士--设置界面&功能列表界面跳转逻辑处理

    在<Android 手机卫士--md5加密过程>中已经实现了加密类,这里接着实现手机防盗功能 本文地址:http://www.cnblogs.com/wuyudong/p/5941959. ...

  5. iOS 疑难杂症 — — UIButton 点击卡顿/延迟

    前言 一开始还以为代码写的有问题,点击事件里面有比较耗时卡主线程的代码,逐一删减代码发现并不是这么回事. 声明  欢迎转载,但请保留文章原始出处:)  博客园:http://www.cnblogs.c ...

  6. Socket.IO聊天室~简单实用

    小编心语:大家过完圣诞准备迎元旦吧~小编在这里预祝大家元旦快乐!!这一次要分享的东西小编也不是很懂啊,总之小编把它拿出来是觉地比较稀奇,而且程序也没有那么难,是一个比较简单的程序,大家可以多多试试~ ...

  7. Mac上idea快捷键

    名称 快捷键 代码提示 ctrl + space 自动修正 alt + enter 查看调用链call hierarchy ctrl + H 查找文件 双击shift 查找类 command + N ...

  8. TFS 10周年生日快乐 – TFS与布莱恩大叔的故事

    今天看了一下Brian Harry大叔的博客,才发现2016年3月17日,是Team Foundation Server的10岁生日. Today marks the 10th anniversary ...

  9. -bash: ulimit: pipe size: cannot modify limit: Invalid argument

    从root账号切换到oracle账号时,出现了"-bash: ulimit: pipe size: cannot modify limit: Invalid argument"提示 ...

  10. ORA-01336: specified dictionary file cannot be opened

    这篇介绍使用Logminer时遇到ORA-01336: specified dictionary file cannot be opened错误的各种场景 1:dictionary_location参 ...