18. 4Sum Medium

来源:互联网 发布:修改手机mac软件 编辑:程序博客网 时间:2024/06/06 14:17

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.


思路: 几数和问题一般思路是固定其中的一些加数,通过其他加数的变化来获得所有加数的集合。这题我们使用固定前两个加数,变化后两个加数的方法。注意因为所得结果不能有重复,我们利用map进行去重操作。


class Solution {public:    vector<vector<int>> fourSum(vector<int>& nums, int target) {        if (nums.size() < 4) {            return vector<vector<int>>();        }        int leng = nums.size();        vector<vector<int>> result;        sort(nums.begin(), nums.end());        map<vector<int>, int> hash;        for (int i = 0; i < leng - 3; i++) {            for (int j = i + 1; j < leng - 2; j++) {                int k = j + 1, q = leng - 1;                int temp = target - nums[i] - nums[j];                while (k < q) {                    if (nums[k] + nums[q] == temp) {                        map<vector<int>, int>::iterator it = hash.begin();                         hash.insert(it, pair<vector<int>, int>(vector<int>({nums[i], nums[j], nums[k], nums[q]}), 1));                        q--;                        k++;                    }                     else if (nums[k] + nums[q] > temp) {                        q--;                    }                    else {                        k++;                    }                }            }        }        map<vector<int>, int>::iterator it = hash.begin();           for(; it != hash.end(); it++)               result.push_back(it -> first);         return result;    }};

0 0
原创粉丝点击