3Sum问题
来源:互联网 发布:知枢密院事 编辑:程序博客网 时间:2024/06/13 06:01
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
采用和2Sum相近的思路,这样,算法的复杂度为O(N*longN+N^2)=O(N^2),需要注意的是排过序的数组相邻相同元素不需要再进行计算,可以减少大量运行时间,代码如下:
class Solution {public: set<vector<int>> twoSum2(vector<int> &numbers, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function //match int i = 0; int j = numbers.size()-1; set<vector<int>> ret2; while(i<j){ if(numbers[i]+numbers[j]==target){ vector<int> ret;int minimum = min(min(numbers[i],numbers[j]),-target);int maxmum = max(max(numbers[i],numbers[j]),-target);int midium = 0 - minimum - maxmum; ret.push_back(minimum);ret.push_back(midium);ret.push_back(maxmum);ret2.insert(ret);i++;j--; }else if(numbers[i]+numbers[j]>target){ j--; }else{ i++; } } return ret2; } vector<vector<int> > threeSum(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(num.begin(),num.end()); vector<vector<int>> ret3; //visit each positive number as target and use 2Sum to the left ones int target; set<vector<int>> set3; vector<int>::iterator it = num.begin(); while(it!=num.end()){ if(it!=num.begin() && *it == *(it-1)) { it++;continue;} target =-*it; //erase the element it = num.erase(it); //2Sum2 set<vector<int>> set2 = twoSum2(num,target); set3.insert(set2.begin(),set2.end()); //insert the element num.insert(it,-target); it++; } ret3.insert(ret3.end(),set3.begin(),set3.end()); return ret3; }};
online judge的时间是: 680 milli secs
- 2sum问题和3sum问题
- 3Sum问题
- 3 Sum问题
- leetcode:3Sum问题
- 3-sum问题
- leetcode 3sum问题
- 3Sum问题
- 3-sum问题
- 算法-3Sum问题
- 3-sum问题
- 3-sum问题
- 剖析3-sum问题(Three sum)
- 2sum/3sum/ksum 问题
- 2Sum/3Sum/3SumClosest/4Sum系列问题
- 2sum,3sum,4sum问题总结
- 2Sum,3Sum,4Sum问题总结
- 【算法】2SUM/3SUM/4SUM问题
- 3sum colsest的问题
- php中$符号切割数据
- iOS cocos2d 实现RollNumber(数字滚动效果)控件效果源码
- iphone ios 屏幕,statusbar,状态栏,标签栏尺寸,高度
- struts2(3)
- C# 网络编程系列六:UDP编程
- 3Sum问题
- 2Sum Problem
- 3Sum Closet
- 4Sum Problem
- JS检查表单
- BOEX3.1备份
- ios cocos2d实现progress(进度条)效果控件源码
- POJ分类
- JAVA中的泛型