18. 4Sum 题解
来源:互联网 发布:dede 修改服务器域名 编辑:程序博客网 时间:2024/05/28 03:01
18. 4Sum 题解
题目描述:
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]]
题目链接:18. 4Sum
算法描述:
由题意知,给定一个数组和一个目标值,判断原数组中是否存在一个四元子数组,它们的和为目标值,找到所有不重复的四元子数组,并且将它们存入集合。
构造结果容器 ans。判断数组长度,如果小于4,返回 ans,否则先对数组进行处理,按照题目的要求,返回的四元子数组是按照增序排列,因此,先对原数组进行排序。
我们用循环遍历的方法来做,首先最外层用两个 for 循环并对四个元素的前两个元素:first 和 second 设置标签,接着设置后两个元素 third 和 forth ,利用 while 循环从两边向中间遍历。当四个元素的和为目标值时,将四个元素放入结果容器 ans 中。否则按照四元素的和与目标值的大小关系调整 third 和 forth 的位置,当 third 的位置不再小于 forth 的位置时结束 while 循环。之后在 for 循环中依次更新 second 的位置和 first 的位置。
注意在遍历时去重。
代码:
class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> ans; int len = nums.size(); if(len < 4){ return ans; } sort(nums.begin(), nums.end()); for(int first = 0; first < len-3; ++first){ for(int second = first + 1; second < len-2; ++second){ int third = second + 1; int forth = len - 1; int tem_target=target-nums[first]-nums[second]; while(third < forth){ if(nums[third]+nums[forth]==tem_target){ ans.push_back(vector<int>({nums[first], nums[second], nums[third], nums[forth]})); while(nums[third] == nums[third + 1]){ ++third; } while(nums[second] == nums[second + 1]){ ++second; } while(nums[first] == nums[first +1]){ ++first; } ++third; } else if(nums[third]+nums[forth]>tem_target){ --forth; } else{ ++third; } } } } return ans; }};
- 18. 4Sum 题解
- leetcode题解-18. 4Sum
- 18. 4Sum LeetCode题解
- Leetcode题解-18. 4Sum
- leetcode题解-18. 4Sum
- 4 sum题解(K sum)
- LeetCode Algorithms 18. 4Sum 题解
- LeetCode题解:4Sum
- Lintcode58 4Sum solution 题解
- LeetCodet题解--18. 4Sum(4个数的和)
- 题解——Leetcode 18. 4Sum 难度:Medium
- LeetCode 题解(17): 4Sum
- LeetCode题解——4SUm
- LeetCode – 4Sum (Java)题解
- 《LeetBook》leetcode题解(18) : 4Sum[M]
- LeetCode 454 4Sum II 题解
- leetcode题解-454. 4Sum II
- 【LeetCode】4sum k-Sum 题解报告及总结
- TextWatcher参数理解
- activiti 数据库核心关系表
- RadioButton界面显隐
- BAT三家的CDN情况究竟如何
- UVA.10986 Fractions Again (经典暴力)
- 18. 4Sum 题解
- Android之JSON的三种解析方式
- 多线程的三种方式
- C++函数之函数与数组
- python——高阶函数——map reduce filter sorted
- Android开源项目LifeUtil 之数据展示
- 即拿即用-Android单线程断点下载
- C/C++ 共用体
- java的多线程(一)