【leetcode】 4 sum
来源:互联网 发布:uvwxyz.xyz index.php 编辑:程序博客网 时间:2024/04/27 14:19
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:
- 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)
class Solution {public: vector<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > results; if (num.size()<3) return results; vector<int> result; result.resize(4); sort(num.begin(),num.end()); int len = num.size(); for (int i = 0; i<len-3; i++){ if (i>0 && num[i]==num[i-1]) continue; int num_1 = num[i]; result[0] = num_1; for (int j = i+1; j < len-2; j++){ if (j>i+1 && num[j]==num[j-1]) continue; int num_2 = num[j]; result[1] = num_2; int left = j+1; int right = len-1; int value = num_1+num_2; while(left<right){ if (left!=j+1&&num[left]==num[left-1]){ left++; continue; } if (right!=len-1&&num[right]==num[right+1]){ right--; continue; } if (value+num[left]+num[right] == target){ result[2] = num[left]; result[3] = num[right]; results.push_back(result); left++; right--; } else if (value+num[left]+num[right] < target){ left++; } else right--; } } } return results; }};
1. 亲,记得sort啊,3 sum往,3 sum closest忘,现在还是忘!!!
2. 几个去重复,很重要!
也可以用hash table来去重复,个人觉得不如这样效率高
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- 程序员面试100题之36在字符串中删除特定的字符
- Linux常用命令
- 找出一个bst中第二大的数
- HBase源代码调试(2)
- 项目管理心得:一个项目经理的个人体会、经验总结
- 【leetcode】 4 sum
- Java基础_环境变量
- [免费] 微软TFS 2012云服务
- 本人简介
- android开发实录
- 资源推荐 五个常用MySQL图形化管理工具
- 了解javascript中的内存泄漏
- 《那些年啊,那些事——一个程序员的奋斗史》——127
- C++成长历程 之 玩转数组