4Sum

来源:互联网 发布:return在c语言中的用法 编辑:程序博客网 时间:2024/06/03 08:14

题目: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)

思路:

先是保存前面数字两两之和,接下来,和之前一样,上来就是两个循环,如果有重复的,continue。

后面就是看是不是有target-num[i]-num[j],有的话,则开始最重要的程序了,首先,看hash里面的第一个数值是否大于刚刚的j,因为我们是从后往前的。不可能小于。

还有就是要区分是否是第一次放进去,如果第二次放进去的话,那么,就需要考虑 res中倒数第二个数,不能够和hash表第一个数相同。

因为此时,第一个,第二个数都是相同的,第三个数相同,那么第四个一定相同。

代码:

class Solution {public://http://www.cnblogs.com/tenosdoit/p/3649607.html  非常好的一篇博客    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;        sort(num.begin(),num.end());        //先保存 前面两数的和        for(int i=0;i<=n-2;i++){            for(int j=i+1;j<=n-1;j++){                pairs[num[i]+num[j]].push_back(make_pair(i,j));            }        }                for(int i=0;i<=n-4;i++){            if(i>0&&num[i]==num[i-1])   continue;//避免重复元素            for(int j=i+1;j<=n-3;j++){                if(j>i+1&&num[j]==num[j-1])     continue;                                if(pairs.find(target-num[i]-num[j])!=pairs.end()){                    bool isFirstPush=true;                    vector< pair<int,int> > sum2=pairs[target-num[i]-num[j]];                    for(int k=0;k<sum2.size();k++){                        if(sum2[k].first<=j)     continue;//新找出来的数组索引值一定要大于之前的两个索引值,i,j                        if(isFirstPush||(res.back())[2]!=num[sum2[k].first]){                            res.push_back(vector<int>{num[i],num[j],num[sum2[k].first],num[sum2[k].second]});                            isFirstPush=false;                            //这里较难理解,因为我第一次可以有重复 1 2 2 3,但是第二次就不行                            //如果有1 2 2,第四个数字一定是3,就一定会重复                        }                    }                }            }        }                return res;    }};


0 0