Leetcode 18 - 4Sum

题目

https://leetcode.com/problems/4sum/

题意

给出一个整数序列和一个数值target,对于这个序列中任意四个数有可能等于target。

请返回和等于target的四个数的所有情况。

Example:

Given array nums = [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]
]

思路

author's blog == http://www.cnblogs.com/toulanboy/

这道题是3Sum的拓展。

思路很简单,我们只需将第1个数固定,然后去讨论3sum的情况即可。

如果不懂3Sum的解法,可以参考https://www.cnblogs.com/toulanboy/p/10900105.html。

代码

//author's blog == http://www.cnblogs.com/toulanboy/
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int i, j, k, p;
        sort(nums.begin(), nums.end());
        vector<vector<int>> result;
        //固定i
        for(i=0; i<(int)nums.size(); ++i){
            if(i != 0 && nums[i] == nums[i-1])
                continue;
            if(target > 0 && nums[i] > target)
                return result;
            //剩余的逻辑和求3个和一样,逻辑讲解:https://www.cnblogs.com/toulanboy/p/10900105.html
            for(j = i+1; j<(int)nums.size()-2; ++j){
                if(j != i+1 && nums[j] == nums[j-1])
                    continue;
                
                k = j+1;
                p = nums.size() - 1;
                while(k < p){
                    int sum = nums[i] + nums[j] + nums[k] + nums[p];
                    if(sum == target){
                        vector<int> tmp;
                        tmp.push_back(nums[i]);
                        tmp.push_back(nums[j]);
                        tmp.push_back(nums[k]);
                        tmp.push_back(nums[p]);
                        result.push_back(tmp);
                    }
                    if(sum <= target){
                        while(k < p && nums[k+1] == nums[k]){
                            k++;
                        }
                        k++;
                    }
                    else if(sum > target){
                        while(k < p && nums[p-1] == nums[p]){
                            p--;
                        }
                        p--;
                    }
                }
        
            }
            
        }
        return result;
    }
};//author's blog == http://www.cnblogs.com/toulanboy/

运行结果

Runtime: 48 ms
Memory Usage: 9.4 MB

转载于:https://www.cnblogs.com/toulanboy/p/10913545.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值