LintCode 58 四个数之和
来源:互联网 发布:而立不惑知天命的含义 编辑:程序博客网 时间:2024/05/17 09:23
题目:fourSum
要求:
给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
注意事项
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
样例:
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
算法要求:
无
解题思路:
跟上一题一样,直接暴力求解,但是四重循环后超时,所以改良一下,用前后查找法找最后二个数。
算法如下:
vector<vector<int> > fourSum(vector<int> nums, int target) { // write your code here vector<vector<int> > vec; set<vector<int> > s; sort(nums.begin(), nums.end()); int size = nums.size(); int mun; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { mun = nums[i] + nums[j]; int k = j + 1, l = size - 1; while (k < l) { int sum = mun + nums[k] + nums[l]; if (sum == target) { vector<int> tempVec; tempVec.push_back(nums[i]); tempVec.push_back(nums[j]); tempVec.push_back(nums[k]); tempVec.push_back(nums[l]); s.insert(tempVec); k++; l--; } else if (sum < target) { k++; } else { l--; } } } } set<vector<int> >::iterator it; for (it = s.begin(); it != s.end(); it++) { vec.push_back(*it); } return vec; }
0 0
- LintCode 58 四个数之和
- lintcode(58)四数之和
- Lintcode 两数之和
- LintCode 三数之和
- LintCode 两数之和
- LintCode 三数之和
- LintCode: 三数之和
- lintcode,三数之和
- Lintcode 三数之和
- LintCode-两数之和
- LintCode 两数之和
- lintcode--两数之和
- [Lintcode]三数之和
- lintcode-- 四数之和
- lintcode--三数之和
- lintcode 两数之和
- lintcode 三数之和
- LintCode-两数之和
- struts2中的constant配置详解
- 初学者关于c语言中函数局部变量空间释放的理解
- 对于输出的字符串进行反向输出(不包括汉字)
- 557. Reverse Words in a String III
- U盘只剩下一个快捷方式,解决办法
- LintCode 58 四个数之和
- hibernate系列(2)之getHibernateTemplate()
- UVALive 7303Aquarium 最小生成树
- servlet context cache 综合
- Minimum’s Revenge
- 51nod_1242 斐波那契数列的第N项
- Hello World — 一个辽宁省OIer的自述
- Java保留字_final
- iOS开发Debug之UIAlertViewController在iPad弹出崩溃问题