LeetCode 18 4Sum
2016-04-09 13:14
447 查看
18. 4Sum
Total Accepted:68829 Total Submissions:
291751 Difficulty: Medium
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:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie,
a ≤ b ≤ c ≤ d)
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)
Subscribe to see which companies asked this question
Have you met this question in a real interview?
找4个数,加起来等于target.
还是一样的方法
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { set<vector<int>> vis; vector<vector<int>> ret; int len=nums.size(); sort(nums.begin(),nums.end()); for(int i=0;i<len;i++) for(int j=i+1;j<len;j++) { int l=j+1,r=len-1; while(l<r) { int temp=nums[i]+nums[j]+nums[l]+nums[r]; if(temp==target) { vector<int> cur; cur.push_back(nums[i]); cur.push_back(nums[j]); cur.push_back(nums[l]); cur.push_back(nums[r]); vis.insert(cur); l++; r--; } else if(temp<target) l++; else r--; } } for(set<vector<int>>::iterator it = vis.begin(); it != vis.end(); it++) ret.push_back(*it); return ret; } };
相关文章推荐
- 【数字智能三篇】之一: 一页纸说清楚“什么是大数据”
- CentOS下LAMP网站架构之Apache性能调优篇
- Nancy之结合tinyfox给我们的应用提供简单的数据服务
- 网站性能优化
- 使用hadoop实现关联商品统计
- POSIX 线程编程小结
- MFC之picture控件滚动条的实现
- 二分 小结
- Angle Admin Template 介绍
- 快速排序递归与非递归
- 第三次作业 价值观作业
- 专用于高并发的map类-----Map的并发处理(ConcurrentHashMap)
- Spring参考指南
- 基于深度学习的图像识别进展:百度的若干实践
- 《Linux内核分析》第七周学习总结
- R语言中的matrix(矩阵),list(列表),data.frame(数据框)总结
- C和指针笔记
- curl模拟post请求提交
- POJ 3026 Borg Maze
- linux命令(9)设定固定ip