18. 4Sum 题解

来源:互联网 发布:dede 修改服务器域名 编辑:程序博客网 时间:2024/05/28 03:01

18. 4Sum  题解



题目描述:


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: 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]]


题目链接:18. 4Sum




算法描述:


             由题意知,给定一个数组和一个目标值,判断原数组中是否存在一个四元子数组,它们的和为目标值,找到所有不重复的四元子数组,并且将它们存入集合。


        构造结果容器 ans。判断数组长度,如果小于4,返回 ans,否则先对数组进行处理,按照题目的要求,返回的四元子数组是按照增序排列,因此,先对原数组进行排序。


        我们用循环遍历的方法来做,首先最外层用两个 for 循环并对四个元素的前两个元素:first 和 second 设置标签,接着设置后两个元素 third 和 forth ,利用 while 循环从两边向中间遍历。当四个元素的和为目标值时,将四个元素放入结果容器 ans 中。否则按照四元素的和与目标值的大小关系调整 third 和 forth 的位置,当 third 的位置不再小于 forth 的位置时结束 while 循环。之后在 for 循环中依次更新 second 的位置和 first 的位置。


        注意在遍历时去重。



代码:

class Solution {public:    vector<vector<int>> fourSum(vector<int>& nums, int target) {                vector<vector<int>> ans;        int len = nums.size();        if(len < 4){            return ans;        }        sort(nums.begin(), nums.end());        for(int first = 0; first < len-3; ++first){            for(int second = first + 1; second < len-2; ++second){                int third = second + 1;                int forth = len - 1;                int tem_target=target-nums[first]-nums[second];                while(third < forth){                    if(nums[third]+nums[forth]==tem_target){                        ans.push_back(vector<int>({nums[first], nums[second], nums[third], nums[forth]}));                        while(nums[third] == nums[third + 1]){                            ++third;                        }                        while(nums[second] == nums[second + 1]){                            ++second;                        }                        while(nums[first] == nums[first +1]){                            ++first;                        }                        ++third;                    }                                        else if(nums[third]+nums[forth]>tem_target){                        --forth;                    }                    else{                        ++third;                    }                }            }        }        return ans;    }};








0 0
原创粉丝点击