#58 4Sum

来源:互联网 发布:nginx 判断变量为空 编辑:程序博客网 时间:2024/05/21 17:00

题目描述:

Given an array S of n integers, are there elements abc, andd in S such that a + b + c + d = target?

Find all unique quadruplets in the array which gives the sum of target.

 Notice

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.

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)
题目思路:

这题和3 sum差不多,只是多了一个未知数。那加一层循环就可以用two pointers的算法了。

Mycode(AC = 291ms):

class Solution {public:    /**     * @param numbers: Give an array numbersbers of n integer     * @param target: you need to find four elements that's sum of target     * @return: Find all unique quadruplets in the array which gives the sum of      *          zero.     */    vector<vector<int> > fourSum(vector<int> nums, int target) {        // write your code here        vector<vector<int>> ans;        if (nums.size() <= 3) return ans;                sort(nums.begin(), nums.end());                set<vector<int>> visited;        for (int i = 3; i < nums.size(); i++) {            for (int j = 2; j < i; j++) {                                // use two pointers method to search                // rest of 2 numbers                int l = 0, r = j - 1;                while (l < r) {                    int sum = nums[l] + nums[r] + nums[j] + nums[i];                    if (sum == target) {                        if (visited.find({nums[l], nums[r], nums[j], nums[i]}) == visited.end()) {                            ans.push_back({nums[l], nums[r], nums[j], nums[i]});                            visited.insert({nums[l], nums[r], nums[j], nums[i]});                        }                                                l++;                        r--;                    }                    else if (sum < target) {                        l++;                    }                    else {                        r--;                    }                }            }        }                return ans;    }};


0 0
原创粉丝点击