2sum、3sum、3close_sum、4sum

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

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //使用一个哈希表来解,第一遍扫描,保存到哈希表中,第二遍扫,看target-n在不在哈希表中,时间复杂度为O(n)。
        //nums=[2,2,6,3,2],target=4,按照题意,最后返回的应该是{0,4}。
        //nums=[1,2,6,2,2],target=3,按照题意,最后返回的应该是{0,4}。
        //nums=[2,2,6,3,2],target=6,按照题意,最后返回的应该是{-1,-1}。特殊情况
        map<int, int> mapping;
        vector<int> res={-1,-1};
        for (int i = 0; i < nums.size(); ++i)
            mapping[nums[i]] = i;//因为题目的测试案例是要返回{0,4},所以这里在mapping里,当元素相同时,存放的是最后一个相同元素的下标
        for(int i = 0; i < nums.size(); i++) {
            int searched = target - nums[i];
            if(mapping.find(searched) != mapping.end() && i != mapping[searched]) {
                res[0]=i+1;
                res[1]=mapping[searched]+1;
                break;
            }
        }
        return res;
    }
};

题目二:
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, 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)
    {
        vector<vector<int> > res;
        vector<int> temp;
        sort(num.begin(),num.end());
        if(num.size() < 3) return res;

        for(int i=0;i<num.size();i++)
            {
            //去掉重复的元素
            if(i>0 && num[i]==num[i-1])
                continue;
            int j=i+1;
            int k=num.size()-1;

            while(j<k)
                {
                int sum=num[i]+num[k]+num[j];
                if(sum==0)
                    {
                    temp.push_back(num[i]);
                    temp.push_back(num[j]);
                    temp.push_back(num[k]);

                    res.push_back(temp);

                    temp.clear();
                    //去掉重复的元素
                    int x=j;
                    while(x<k && num[x]==num[j])
                        x++;
                    j=x;

                    x=k;
                    while(x>j && num[x]==num[k])
                        x--;
                    k=x;
                }
                else if(sum>0)
                    k--;
                else
                    j++;
            }

        }
        //sort(res.begin(),res.end());
        //res.erase(unique(res.begin(),res.end()),res.end());
        return res;
    }
};

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

class Solution {
    public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(),num.end());
        //result_sum里面永远记录的都是当前最接近target的值
        int result_sum=num[0]+num[1]+num[num.size()-1];//这里不能把pre初始化成INT_MAX,否则的话在abs(presum-target)这一步会溢出
        for(int i=0;i<num.size()-1;i++)
        {
            int j=i+1,k=num.size()-1;
            while(j<k)
            {
                int cursum=num[i]+num[j]+num[k];
                if(abs(cursum-target)<abs(result_sum-target))
                    result_sum=cursum;

                if(result_sum==target)
                    return result_sum;
                else if(cursum>target)
                    k--;
                else
                    j++;
            }
        }
        return result_sum;
    }
};

题目四:
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, 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)
class Solution {
    public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
       sort(num.begin(),num.end());
        vector<vector<int>> res;

        if(num.size()<=3) return res;


        for(int i=0;i<num.size()-3;i++)
        {
            //去掉重复的元素
            if(i>0 && num[i]==num[i-1])
                continue;

            for(int j=i+1;j<num.size()-2;j++)
            {
                //去掉重复的元素
                if(j>i+1 && num[j]==num[j-1])
                    continue;

                int k=j+1,p=num.size()-1;              
                while(k<p)
                {
                    int sum=num[i]+num[j]+num[k]+num[p];
                    if(sum==target)
                    {
                        vector<int> tmp;
                        tmp.push_back(num[i]);
                        tmp.push_back(num[j]);
                        tmp.push_back(num[k]);
                        tmp.push_back(num[p]);
                        res.push_back(tmp);

                        //去掉重复的元素
                        //首先去掉跟num[j]相等的元素
                        int x=k;
                        while(x<num.size() && num[x]==num[k])
                            x++;
                        k=x;

                        //再去掉跟num[p]相等的元素
                        x=p;
                        while(x>=0 && num[x]==num[p])
                            x--;
                        p=x;
                    }
                    else if(sum<target)
                        k++;
                    else
                        p--;
                }
            }
        }
        return res;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值