2sum 3sum 4sum 各种sum

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题目:在一个数组中,找到两个数的和是target。题目假设仅有一个解。

分析:本来是很简单的一个题目,排序,然后定义两个下标i,j分别从头和尾向中间夹逼,直到找到和为target的下标。时间复杂度是排序的O(nlogn)。

问题的复杂在于返回下标,因为排序会打乱下标,因此需要定义一个数据结构来保存下标和对应的值,值排序之后,返回对应的结果。

代码:

struct Node {
    int val;
    int index;
    Node(int v, int i):val(v),index(i){}
};

bool cmp(const Node &n1, const Node &n2){//比较函数,注意参数要const...
    return (n1.val < n2.val);
}

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> res;
        int len=numbers.size();
        if(len<2) return res;
        vector<Node> tmp;
        for(int x=0;x<len;x++){
            Node n(numbers[x],x);
            //将新的节点push到容器中
            tmp.push_back(n);
        }
        sort(tmp.begin(), tmp.end(),cmp);//排序
        
        int i,j;
        for(i=0,j=len-1;i<j;){//两下标
            if((tmp[i].val+tmp[j].val)<target){
                i++;
            }else if((tmp[i].val+tmp[j].val)>target){
                j--;
            }else{//==
                if(tmp[i].index<tmp[j].index){//注意结果保证小小标在前
                    res.push_back(tmp[i].index+1);
                    res.push_back(tmp[j].index+1);
                }else{
                    res.push_back(tmp[j].index+1);
                    res.push_back(tmp[i].index+1);
                   
                }      
                break;
            }
        }
        return res;
    }
};

3Sum

Given an array S of n integers, are there elements a, b, c 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, abc)
  • 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)
题目:在数组中找到三个数,使和为0,可能有多组这样的数满足结果。

分析:基本思路,固定一个数,然后target减去这个数,转换成2sum问题,时间复杂度为O(n*nlogn)。

这里注意去重,找到一个满足条件的结果后,要将i之后与当前值相同的 屏蔽掉,j同样。

代码:

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        int len=num.size();
        vector<vector<int> > res;
        sort(num.begin(),num.end());
        
        for(int k=0;k<len-2;){
            int t=0-num[k];
            for(int i=k+1,j=len-1;i<j;){//i=k+1!!!!i初始化时错了,单步调试才发现。。。。
                if((num[i]+num[j])>t) j--;
                else if((num[i]+num[j])<t) i++;
                else{//==
                    vector<int> one;
                    one.push_back(num[k]);
                    one.push_back(num[i]);
                    one.push_back(num[j]);
                    res.push_back(one);
                    i++;j--;
                    while(i<j && num[i]==num[i-1])//去除与当前结果相同的值
                        i++;
                    while(j>i && num[j]==num[j+1])
                        j--;
                }
            }//i,j
            k++;
            while(k<len-2 && num[k]==num[k-1])//外层的k也要进行同样的处理
                k++;
        }//for k
        return res;
    }
};


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)
题目: 求一个数组中的三个数,他们之和最接近target。

分析:同样排序,固定一个数,转换成2sum问题,注意这里最接近,保存一个dif来记录最小差值。

代码:

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int len=num.size();
        sort(num.begin(),num.end());
        int closet=0;
        int mindif=INT_MAX;
        for(int i=0;i<len-2;i++){
            int t=target-num[i];
            for(int j=i+1,k=len-1;j<k;){
                int dif=(num[j]+num[k])-t;
                if(abs(dif)<mindif) { //记录最小差值
                    mindif=abs(dif); 
                    closet=num[i]+num[j]+num[k];
                }
                if(dif<0){
                    j++;
                }else if(dif>0){
                    k--;
                }else{
                    return target;
                }
                //if(abs(dif)<mindif) { //不能放在后面,if会是k的值发生变化
                //    mindif=abs(dif); 
                //    closet=num[i]+num[j]+num[k];//此时k已经发生变化
                //}
                
            }//for j k
            
        }//for i
        return closet;
    }
};

4Sum

Given an array S of n integers, are there elements a, b, c, 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, abcd)
  • 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)

题意:从一个数组中,找四个数使其和等于target。

分析:依次固定两个数,也变成2sum的问题,时间复杂度O(n^3log(n)),同样注意去重复。

代码:

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        int len=num.size();
        vector<vector<int> > res;
        if(len<4) return res;
        
        sort(num.begin(),num.end());
        
        for(int k=0;k<len-3;){
            for(int n=k+1;n<len-2;){
                int t=target-num[k]-num[n];
                for(int i=n+1,j=len-1;i<j;){
                    int tar=num[i]+num[j];
                    if(tar==t){//注意这里比较的是 tar和t,不是原来的target了!
                        vector<int> one;
                        one.push_back(num[k]);
                        one.push_back(num[n]);
                        one.push_back(num[i]);
                        one.push_back(num[j]);
                        
                        res.push_back(one);
                        i++;j--;
                        while(i<j && num[i]==num[i-1]) i++;
                        while(j>i && num[j]==num[j+1]) j--;
                        
                    }else if(tar<t){//同t
                        i++;
                    }else{
                        j--;
                    }
                }// for i j
                n++;
                while(n<len-2 && num[n]==num[n-1]) n++;
            }//for n
            k++;
            while(k<len-3 && num[k]==num[k-1]) k++;
        }//for k
        return res;
    }
};
N Sum问题的思路懂了还是比较清晰的,可每次代码都有点小问题。。。要严谨

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值