LeetCode:3Sum, 3Sum Closest, 4Sum

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 Closest 最近三数之和


下一篇:Leetcode 3Sum Closest