15. 3Sum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

15. 3Sum

15. 3Sum

15. 3Sum

leetcode 15 3Sum

[leetcode][15] 3Sum

15. 3Sum