美文网首页
18. 4Sum/四数之和

18. 4Sum/四数之和

作者: 蜜糖_7474 | 来源:发表于2019-05-09 13:52 被阅读0次

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

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

AC代码

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        if (nums.size() < 4) return {};
        sort(nums.begin(), nums.end());
        vector<vector<int>> ret(0);
        set<vector<int>> ans;
        for (int mid1 = 1; mid1 < nums.size() - 2; ++mid1) {
            for (int mid2 = mid1 + 1; mid2 < nums.size() - 1; ++mid2) {
                int left = 0, right = nums.size() - 1;
                while (left < mid1 && mid2 < right) {
                    int sum = nums[left] + nums[mid1] + nums[mid2] + nums[right];
                    if (sum == target) {
                        vector<int> tmp{nums[left], nums[mid1], nums[mid2], nums[right]};
                        ans.insert(tmp);
                        while (right > mid2 && nums[right] == nums[right - 1]) right--;
                        while (left < mid1 && nums[left] == nums[left + 1]) left++;
                        right--;
                        left++;
                    }
                    else if (sum < target) left++;
                    else if (sum > target) right--;
                }
            }
        }
        for (auto it = ans.begin(); it != ans.end(); ++it) {
            vector<int> tmp{(*it)[0], (*it)[1], (*it)[2], (*it)[3]};
            ret.push_back(tmp);
        }
        return ret;
    }
};

总结

3Sum的强化版,思路基本一样,多加判断条件及时退出循环可以使程序运行快三四倍

相关文章

  • 力扣每日一题:18.四数之和

    18.四数之和 https://leetcode-cn.com/problems/4sum/[https://le...

  • 18.四数之和

    18.四数之和 题目链接:https://leetcode-cn.com/problems/4sum/[https...

  • 18. 4Sum/四数之和

    Given an array nums of n integers and an integer target, ...

  • 18. 4Sum 四数之和

    题目 给定一个数组 nums 和目标数 target。找到 四个数字使得这四个数相加等于目标数。 解析 和三数相加...

  • LeetCode每日一题,四数之和

    题目 四数之和[https://leetcode-cn.com/problems/4sum/] https://l...

  • 【Leetcode算法题】18. 四数之和

    By Long Luo 18. 四数之和[https://leetcode-cn.com/problems/4su...

  • LeetCode-18 四数之和

    题目:18. 四数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第18题四数之和,这是一道中等题。像...

  • 18. 四数之和

    一、题目原型: 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四...

  • 18. 四数之和

    知乎ID: 码蹄疾码蹄疾,毕业于哈尔滨工业大学。小米广告第三代广告引擎的设计者、开发者;负责小米应用商店、日历、开...

  • 18. 四数之和

    18.四数之和 给定一个包含n个整数的数组nums和一个目标值target,判断nums中是否存在四个元素a,b,...

网友评论

      本文标题:18. 4Sum/四数之和

      本文链接:https://www.haomeiwen.com/subject/zihwoqtx.html