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

 

 

 

原创粉丝点击