Leetcode题解-18. 4Sum
来源:互联网 发布:windows dvd 播放器 编辑:程序博客网 时间:2024/06/06 06:33
Leetcode题解-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]
]
思路
把4Sum问题化成3Sum,3Sum化成2Sum,所以还是在2Sum的基础上加两重循环。2Sum的思路是:把数组nums从小到大排序,一个指针front指向数组头,一个指针back指向数组尾,如果front和back指向数组元素之和小于target,front++,如果大于target则back–,直到front不小于back结束
代码
vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> res; int l = nums.size(); if(l < 4) return res; sort(nums.begin(), nums.end()); for(int i = 0; i < l-3; i++){ int ttarget = target - nums[i]; for(int j = i+1; j < l-2; j++){ int front = j + 1, back = l - 1, tttarget = ttarget - nums[j]; while(front < back){ int sum = nums[front] + nums[back]; if(sum < tttarget) front++; else if(sum > tttarget) back--; else{ vector<int> tem(4,0); tem[0] = nums[i]; tem[1] = nums[j]; tem[2] = nums[front]; tem[3] = nums[back]; res.push_back(tem); while(front < back && nums[front] == tem[2]) front++; while(front < back && nums[back] == tem[3]) back--; } } while(nums[j] == nums[j+1]) j++; } while(nums[i] == nums[i+1]) i++; } return res; }
阅读全文
0 0
- leetcode题解-18. 4Sum
- 18. 4Sum LeetCode题解
- Leetcode题解-18. 4Sum
- leetcode题解-18. 4Sum
- LeetCode题解:4Sum
- LeetCode Algorithms 18. 4Sum 题解
- 题解——Leetcode 18. 4Sum 难度:Medium
- 18. 4Sum 题解
- LeetCode 题解(17): 4Sum
- LeetCode题解——4SUm
- LeetCode – 4Sum (Java)题解
- 《LeetBook》leetcode题解(18) : 4Sum[M]
- LeetCode 454 4Sum II 题解
- leetcode题解-454. 4Sum II
- LeetCode题解:Two Sum
- LeetCode题解:3Sum
- LeetCode - 3Sum 题解
- LeetCode题解:Path Sum
- View 用 Paint 画出的图形
- mongodb初步学习(二)
- 输出空心菱形
- Linux —— Vim的暂存档(恢复文件内容)
- 文章标题
- Leetcode题解-18. 4Sum
- AngularJs实现表格点击不同字段排序的功能
- Nginx初探
- 看一个接口回调的例子
- mxGraph节点图形设置
- STC12单片机实现自动下载程序
- 内网穿透利器——frp
- java(十二):线程池和ThreadPoolExecutor
- z2