{ "type": "code_options", "author": "csdn.net", "source": "solution.md", "exercise_id": "019e45cad3ba412aa84ebbc18cba97aa", "keywords": "数组,双指针,排序", "title": "四数之和", "desc": [ { "content": "\n

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:答案中不可以包含重复的四元组。

 

示例 1:

输入:nums = [1,0,-1,0,-2,2], target = 0
输出:
[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

示例 2:

输入:nums = [], target = 0
输出:
[]

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "cpp" } ], "prepared": [ [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ] ], "template": { "content": "class Solution\n{\npublic:\n\tvector> fourSum(vector &nums, int target)\n\t{\n\t\tlong long l_target = target;\n\t\tsort(nums.begin(), nums.end());\n\t\tvector> results;\n\t\tint N = nums.size();\n\t\tfor (int i = 0; i < N - 3; i++)\n\t\t{\n\t\t\tif (i > 0 && nums[i] == nums[i - 1])\n\t\t\t\tcontinue;\n\t\t\tfor (int j = i + 1; j < N - 2; j++)\n\t\t\t{\n\t\t\t\tif (j > i + 1 && nums[j] == nums[j - 1])\n\t\t\t\t\tcontinue;\n\t\t\t\tfor (int k = j + 1, l = N - 1; k < l; k++)\n\t\t\t\t{\n\t\t\t\t\tif (k > j + 1 && nums[k] == nums[k - 1])\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\twhile (k < l &&\n\t\t\t\t\t\t (l_target - nums[i] - nums[j] - nums[k] - nums[l]) < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tl--;\n\t\t\t\t\t}\n\t\t\t\t\tif (k >= l)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif ((target - nums[i] - nums[j] - nums[k] - nums[l]) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tresults.emplace_back(\n\t\t\t\t\t\t\tvector({nums[i], nums[j], nums[k], nums[l]}));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n};", "language": "cpp" }, "node_id": "dailycode-015937d27ef34a46b5ef9f61bde201e1", "license": "csdn.net", "created_at": 1637894158, "topic_link": "https://bbs.csdn.net/topics/600469919" }