本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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解法就不适合这里了
 
 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int> &num, int target) {
 4         int n = num.size();
 5         sort(num.begin(), num.end());
 6         int res, dis = INT_MAX;
 7         for(int i = 0; i < n - 2; i++)
 8         {
 9             int target2 = target - num[i], tmpdis;
10             int tmpres = twoSumClosest(num, i+1, target2);
11             if((tmpdis = abs(tmpres - target2)) < dis)
12             {
13                 res = tmpres + num[i];
14                 dis = tmpdis;
15                 if(res == target)
16                     return res;
17             }
18         }
19         return res;
20     }
21     
22     int twoSumClosest(vector<int> &sortedNum, int start, int target)
23     {
24         int head = start, tail = sortedNum.size() - 1;
25         int res, dis = INT_MAX;
26         while(head < tail)
27         {
28             int tmp = sortedNum[head] + sortedNum[tail];
29             if(tmp < target)
30             {
31                 if(target - tmp < dis)
32                 {
33                     res = tmp;
34                     dis = target - tmp;
35                 }
36                 head++;
37             }
38             else if(tmp > target)
39             {
40                 if(tmp - target < dis)
41                 {
42                     res = tmp;
43                     dis = tmp - target;
44                 }
45                 tail--;
46             }
47             else
48                 return target;
49         }
50         return res;
51     }
52 };

 


 

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)

 为了避免重复,对于排序后的数组,当我们枚举第一个数时,如果遇到重复的就直接跳过;当我们找到一个符合的二元组(第二个数和第三个数)时,也分别对第二个数和第三个数去重。具体见代码注释。代码中的两个函数也可以合并成一个。

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) {
 4         int n = num.size();
 5         sort(num.begin(), num.end());
 6         vector<vector<int> > res;
 7         for(int i = 0; i < n-2; i++)
 8         {
 9             if(i > 0 && num[i] == num[i-1])continue;//重复的元素不用计算
10             int target2 = 0 - num[i];
11             twoSum(num, i+1, target2, res);
12         }
13         return res;
14     }
15     void twoSum(vector<int> &sortedNum, int start, int target, vector<vector<int> >&res)
16     {
17         int head = start, tail = sortedNum.size() - 1;
18         while(head < tail)
19         {
20             int tmp = sortedNum[head] + sortedNum[tail];
21             if(tmp < target)
22                 head++;
23             else if(tmp > target)
24                 tail--;
25             else
26             { ;
27                 res.push_back(vector<int>{sortedNum[start-1], sortedNum[head], sortedNum[tail]});
28                 
29                 //为了防止出现重复的二元组,使结果等于target
30                 int k = head+1;
31                 while(k < tail && sortedNum[k] == sortedNum[head])k++;
32                 head = k;
33                 
34                 k = tail-1;
35                 while(k > head && sortedNum[k] == sortedNum[tail])k--;
36                 tail = k;
37             }
38         }
39     }
40 };

 


 

 

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),去重方法和上一题类似
 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4         int n = num.size();
 5         vector<vector<int> > res;
 6         sort(num.begin(), num.end());
 7         for(int i = 0; i < n-3; i++)
 8         {
 9             if(i > 0 && num[i] == num[i-1])continue;//防止第一个元素重复
10             for(int j = i+1; j < n-2; j++)
11             {
12                 if(j > i+1 && num[j] == num[j-1])continue;//防止第二个元素重复
13                 int target2 = target - num[i] - num[j];
14                 int head = j+1, tail = n-1;
15                 while(head < tail)
16                 {
17                     int tmp = num[head] + num[tail];
18                     if(tmp > target2)
19                         tail--;
20                     else if(tmp < target2)
21                         head++;
22                     else
23                     {
24                         res.push_back(vector<int>{num[i], num[j], num[head], num[tail]});
25                         //为了防止出现重复的二元组,使结果等于target2
26                         int k = head+1;
27                         while(k < tail && num[k] == num[head])k++;
28                         head = k;
29                         
30                         k = tail-1;
31                         while(k > head && num[k] == num[tail])k--;
32                         tail = k;
33                     }
34                 }
35             }
36         }
37         return res;
38     }
39 };

算法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)

 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4         int n = num.size();
 5         vector<vector<int> > res;
 6         unordered_map<int, vector<pair<int, int> > >pairs;
 7         pairs.reserve(n*n);
 8         sort(num.begin(), num.end());
 9         
10         for(int i = 0; i < n; i++)
11             for(int j = i+1 ; j < n; j++)
12                 pairs[num[i]+num[j]].push_back(make_pair(i,j));
13         
14         for(int i = 0; i < n - 3; i++)
15         {
16             if(i != 0 && num[i] == num[i-1])continue;//防止第一个元素重复
17             for(int j = i+1; j < n - 2; j++)
18             {
19                 if(j != i+1 && num[j] == num[j-1])continue;//防止第二个元素重复
20                 if(pairs.find(target - num[i] - num[j]) != pairs.end())
21                 {
22                     vector<pair<int, int>> &sum2 = pairs[target - num[i] - num[j]];
23                     bool isFirstPush = true;
24                     for(int k = 0; k < sum2.size(); k++)
25                     {
26                         if(sum2[k].first <= j)continue;//保证所求的四元组的数组下标是递增的
27                         if(isFirstPush || (res.back())[2] != num[sum2[k].first])
28                         {
29                             res.push_back(vector<int>{num[i], num[j], num[sum2[k].first], num[sum2[k].second]});
30                             isFirstPush = false;
31                         }
32                     }
33                 }
34             }
35         }
36         
37         return res;
38     }
39 };

对于k-sum问题,我们可以不断的转化为k-1 sum, k-2 sum 直到2sum;也可以像4sum问题的hashmap解法一样,分成若干个2sum问题。可以参看这篇文章:

k sum problem (k 个数的求和问题)

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3649607.html

posted @ 2014-04-07 00:21  tenos  阅读(10390)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童