【Leetcode】3Sum,3sum closest,3sum smaller, 4Sum

3Sum

// Author : yqtao
// Date   : 2016.6.17
// Email  : yqtao@whu.edu.cn
/**************************************************************************************
*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>& nums) {
        vector<vector<int>> res;
        if (nums.size()<=2) return res;
        sort(nums.begin(),nums.end());
        for (int i=0;i<nums.size()-2;i++) {
            if (i>0&&nums[i]==nums[i-1])  continue;
            int a=nums[i],low=i+1,high=nums.size()-1;
            while (low<high) {
                int b=nums[low],c=nums[high];
                if (a+b+c==0) {
                    vector<int> v;
                    v.push_back(a);
                    v.push_back(b);
                    v.push_back(c);
                    res.push_back(v);
                }
                if (a+b+c>0) {
                    while (low<high&&nums[high]==nums[high-1]) high--;
                    high--;
                }
                else {
                    while (low<high&&nums[low]==nums[low+1]) low++;
                    low++;
                }
            }
        }
        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).
*
*
**********************************************************************************/
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int n=nums.size(),dis=INT_MAX,res=0;
        if (n<3) return -1;
        sort(nums.begin(),nums.end());
        for (int i=0;i<n-2;i++) {
            if (i>0&&nums[i]==nums[i-1]) continue;
            int a=nums[i],low=i+1,high=n-1;
            while (low<high) {
                int b=nums[low],c=nums[high];
                int sum=a+b+c;
                if (dis>abs(target-sum)) {
                    dis=abs(target-sum);
                    if (dis==0) return target;
                    res=sum;
                }
                if (sum>target) {
                    while (low<high&&nums[high]==nums[high-1]) high--;
                    high--;
                }
                else {
                    while (low<high&&nums[low]==nums[low+1]) low++;
                    low++;
                }

            }
        }
        return res;
    }
};

3Sum smaller

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
For example, given nums = [-2, 0, 1, 3], and target = 2.
Return 2. Because there are two triplets which sums are less than 2:
[-2, 0, 1]
[-2, 0, 3]

解析:因为要找三个数相加比target小的,因此只需要移动最右边的指针即可。

int threeSumSmaller(vector<int>&nums, int target){  
    int size = nums.size();  
    sort(nums.begin(),nums.end());  
    int cnt = 0;  
    for(int i = 0;i < size-2;i++){  
        int j = i+1,k = size - 1;  
        while(j < k){  
           int sum = nums[i] + nums[j] + nums[k];             
           if(sum < target)cnt++;  
           k--;    //仅仅移动此指针
        }           
    }  
    return cnt;  
}  

4 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)
*
*
**********************************************************************************/

解析:可以将4sum的问题变成3sum的问题进行求解。

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>&num, int target);
vector<vector<int>> fourSum(vector<int>&num, int target)
{
    vector<vector<int>> result;
    if (num.size() < 4) return result;
    sort(num.begin(), num.end());//首先进行排序
    for (int i = 0; i < num.size() - 3; i++)
    {
        if (i > 0 && num[i - 1] == num[i])
            continue;
        //复制到n中,然后用3sum方法解决
        vector<int>n(num.begin() + i + 1, num.end());
        vector<vector<int>> ret = threeSum(n, target - num[i]);
        for (int j = 0; j < ret.size(); j++)
        {
            ret[j].insert(ret[j].begin(), num[i]);//在结果前插入num[i]
            result.push_back(ret[j]);
        }
    }
    return result;
}
vector<vector<int>> threeSum(vector<int>&num,int target)
{
    vector<vector<int>> result;//返回二维数组
    sort(num.begin(), num.end());//首先进行排序
    int n = num.size();
    for (int i = 0; i < n - 2; i++)// 因为三个数,所以第一个数最大只能为len-3
    {
        //去掉重复值,这里一定要注意,i如果与前一个i所在值相同,则
        //不必计算了,直接另i++
        //不能写成num[i]==num[i+1]
        if (i > 0 && num[i-1] == num[i])
            continue;
        int a = num[i];
        int low = i + 1;
        int high = n - 1;
        while (low < high)
        {
            int b = num[low];
            int c = num[high];
            if (a+b+c==target)//满足条件,将其加入数组中
            {
                vector<int>v;
                v.push_back(a);
                v.push_back(b);
                v.push_back(c);
                result.push_back(v);
                //继续寻找下一个满足条件的值,去重值
                while (low < high&&num[low] == num[low + 1]) low++;
                low++;
                while (high > low&&num[high] == num[high - 1]) high--;
                high--;
            }
            else if (a + b + c>target)
            {
                while (high > low&&num[high] == num[high - 1])
                    high--;
                high--;
            }
            else
            {
                while (low < high&&num[low] == num[low + 1]) 
                    low++;
                low++;
            }

        }
    }
    return result;
}
//打印二维数组
void printMatrix(vector<vector<int>> &matrix)
{
    //基于范围for循环,等效于下面的for
    for (auto c : matrix)
    {
        cout << "[";
        for (auto r : c)
            cout << r << " ";
        cout <<"]"<< endl;
    }
    /*for (int i = 0; i < matrix.size(); i++)
    {
    cout << "[";
    for (int j = 0; j < matrix[i].size(); j++)
    cout << matrix[i][j] << "  ";
    cout << "]" << endl;
    }*/
}
int main()
{
    vector<int>num = { 1, 0, -1, 0, - 2, 2 };
    vector<vector<int>>result = fourSum(num,0);
    printMatrix(result);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值