4Sum
来源:互联网 发布:格力壁挂空调 r32知乎 编辑:程序博客网 时间:2024/06/05 19:31
题目描述:
Given an array S of n integers, are there elements a, b, c, 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.
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]]解题思路:
类似于题目3Sum,不同之处是这里需要固定两个数字,3Sum的解题思路可以参考:3Sum
AC代码如下:
class Solution {public:vector<vector<int>> fourSum(vector<int>& nums, int target) {vector<vector<int>> res;int numlen = nums.size();if (nums.size()<4) return res;sort(nums.begin(), nums.end());for (int i = 0; i < numlen; i++){if (i != 0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组for (int j = i + 1; j < numlen; j++){if (j != i + 1 && nums[j] == nums[j - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组int begin = j + 1;int end = numlen - 1;while (begin < end){int sum = nums[i] + nums[j] + nums[begin] + nums[end];if (sum == target){vector<int> tmp = {nums[i],nums[j],nums[begin],nums[end]};res.push_back(tmp);while (++begin<end && nums[begin] == nums[begin - 1]); //跳过重复的元素,避免结果中出现重复的四元组while (--end>begin && nums[end] == nums[end + 1]); //跳过重复的元素,避免结果中出现重复的四元组}else if (sum<target)begin++;elseend--;}}}return res;}};
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 2Sum 3Sum 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 面试题33:把数组排成最小的数
- fork 之 父子进程
- PHP AOP 面向切面
- easyui.utils.js 自己封装的 使用easyui过程中方便操作和取值(一)
- 快速阅读
- 4Sum
- VMware使用共享文件夹
- hdu 5645(取球&&概率)
- linux 根据进程名查看其占用的端口
- 去除字符串中重复的字符
- python点滴:读取和整合文件夹下的所有文件
- Maven学习笔记(三)——使用Maven构件web项目
- Animation从左边开始缩放
- javascript的重要性