LeetCode:3Sum, 3Sum Closest, 4Sum

时间:2022-11-12 22:00:13

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. 求和问题总结&lpar;leetcode 2Sum&comma; 3Sum&comma; 4Sum&comma; K Sum&rpar;

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

  2. LeetCode 16&period; 3Sum Closest&lpar;最接近的三数之和&rpar;

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

  3. &lbrack;Leetcode&rsqb;&lbrack;016&rsqb; 3Sum Closest &lpar;Java&rpar;

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

  4. &lbrack;LeetCode&rsqb; 15&period; 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. &lbrack;LeetCode&rsqb; 259&period; 3Sum Smaller 三数之和较小值

    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 &lt ...

  6. LeetCode 15 3Sum &lbrack;sort&rsqb; &lt&semi;c&plus;&plus;&gt&semi;

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

  7. LeetCode之&OpenCurlyDoubleQuote;散列表”:Two Sum &amp&semi;&amp&semi; 3Sum &amp&semi;&amp&semi; 3Sum Closest &amp&semi;&amp&semi; 4Sum

    1. Two Sum 题目链接 题目要求: Given an array of integers, find two numbers such that they add up to a specif ...

  8. LeetCode 15&period; 3Sum 16&period; 3Sum Closest 18&period; 4Sum

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

  9. LeetCode &lpar;13&rpar;&colon; 3Sum Closest

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

随机推荐

  1. CSS使用自定义光标样式-遁地龙卷风

    测试环境是chrome浏览器 Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357. ...

  2. iOS Architecture Patterns

    By Bohdan Orlov on 21 Mar 2016 - 0 Comments iOS FYI: Slides from my presentation at NSLondon are ava ...

  3. editplus的各式插件

    C/C++, Java, JSP, C#, .NET, SQL, Pascal, Python, Assembly, Basic files http://www.editplus.com/javac ...

  4. matlab 之基础使用

    dir(xxx,'.jpg') :读取某文件所有jpg格式的图片,并获取图片属性信息 size(x,1) :获得x矩阵多少行 cell(): 申明数组 注释选定代码的快捷操作:Ctrl+R

  5. 修改ubuntu按下关机键触发的事件

    gsettings set org.gnome.settings-daemon.plugins.power button-power shutdown will change your the beh ...

  6. xss&lpar;跨站脚本攻击&rpar;,crsf&lpar;跨站请求伪造&rpar;,xssf

    我们常说的网络安全其实应该包括以下三方面的安全: 1.机密性,比如用户的隐私被窃取,帐号被盗,常见的方式是木马. 2.完整性,比如数据的完整,举个例子,康熙传位十四子,被当时四阿哥篡改遗诏:传位于四子 ...

  7. AngularJs学习笔记2-控制器、数据绑定、作用域

    上次分享完该系列文章后有朋友也建议说1.x版本除了维护也没有必要学习,可以学习2.0开始学习,我也知道1.x无论是从性能还是架构上都没有2.x好,但是我想因为现在也有一些朋友还在用1.x版本,因为1. ...

  8. Redis开启远程登录连接

    Redis 安装详见 http://www.cnblogs.com/zendwang/p/6560628.html 当前安装测试版本:Redis 3.2.8 默认安装完毕Redis只能本机访问 [ro ...

  9. CSS3中三角形及三角形组合图实现

        几何之三角形及三角形的组合图案理论 三角形( triangle ['traɪæŋɡl])可以看成正方形对角线交叉形成的图形 若想得到编号①方向向下三角形,只需对编号②③④三角形让其透明tran ...

  10. C&num; 移除Response Header,403调整返回为404Make IIS return a 404 status code instead of 403

    Server Information Revealed For the benefit of those who land here through a google/bing search:: He ...