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

  • 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)

LeetCode中关于数字之和还有其他几道,分别是Two Sum 两数之和3Sum 三数之和3Sum Closest 最近三数之和,虽然难度在递增,但是整体的套路都是一样的,在这里为了避免重复项,我们使用了STL中的set,其特点是不能有重复,如果新加入的数在set中原本就存在的话,插入操作就会失败,这样能很好的避免的重复项的存在。此题的O(n^3)解法的思路跟3Sum 三数之和基本没啥区别,就是多加了一层for循环,其他的都一样,代码如下:

// O(n^3)
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &nums, int target) {
        set<vector<int> > res;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < int(nums.size() - 3); ++i) {
            for (int j = i + 1; j < int(nums.size() - 2); ++j) {
                int left = j + 1, right = nums.size() - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        vector<int> out;
                        out.push_back(nums[i]);
                        out.push_back(nums[j]);
                        out.push_back(nums[left]);
                        out.push_back(nums[right]);
                        res.insert(out);
                        ++left; --right;
                    } else if (sum < target) ++left;
                    else --right;
                }
            }
        }
        return vector<vector<int> > (res.begin(), res.end());
    }
};

本文转自博客园Grandyang的博客,原文链接:四数之和[LeetCode] 4Sum ,如需转载请自行联系原博主。

相关文章
|
1月前
|
算法 测试技术
每日一题:LeetCode-LCR 007. 三数之和
每日一题:LeetCode-LCR 007. 三数之和
|
4月前
leetcode-54:螺旋矩阵
leetcode-54:螺旋矩阵
21 0
|
4月前
|
Java C++ Python
leetcode-59:螺旋矩阵 II
leetcode-59:螺旋矩阵 II
19 0
|
5月前
牛客网 KY11 二叉树遍历
牛客网 KY11 二叉树遍历
23 0
|
11月前
|
算法 安全 Swift
LeetCode - #54 螺旋矩阵
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
LeetCode - #54 螺旋矩阵
|
11月前
|
算法 安全 Swift
LeetCode - #59 螺旋矩阵 II
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
LeetCode - #59 螺旋矩阵 II
|
11月前
leetcode:54.螺旋矩阵
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
35 0
|
11月前
|
机器学习/深度学习 Java Python
leetcode:59.螺旋矩阵II
leetcode:59.螺旋矩阵II
51 0
|
12月前
|
算法
LeetCode每日1题--螺旋矩阵
LeetCode每日1题--螺旋矩阵
49 0
LeetCode每日1题--螺旋矩阵
|
12月前
|
算法
LeetCode每日1题--四数之和
LeetCode每日1题--四数之和
57 0