首页 > 代码库 > 15. 3Sum

15. 3Sum

 

此问题可以分解为:当一个值确定,判断剩余的数中是否存在两个和为此数

需要检测完全

 

class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) 
  {
      sort(nums.begin(),nums.end());
      vector <vector <int> > res;
      int target=0;
      for(auto iter = nums.begin();iter!=nums.end();iter++)
      {
           target= -*iter;

          auto  front = iter+1;
          auto  back = nums.end()-1;
          while(front < back)
          {
              int sum = *front + *back;
              if(sum < target)
              {
                  front++;
              }
              else if(sum > target)
              {
                  back--;
              }
              else
              {
                  vector<int> one;
                  one.push_back(-target);
                  one.push_back(*front);
                  one.push_back(*back);
                  res.push_back(one);
                  while(front < back && *front == one[1] )front++;
                  while(front < back && *back  == one[2] )back--;
              }
          }
          while( (iter+1) <nums.end()&&*(iter+1)==*(iter))iter++;
      }
      return res;
  }

};

 

15. 3Sum