15. 3Sum

来源:互联网 发布:知乎 王师 编辑:程序博客网 时间:2024/06/04 00:16
  1. class Solution {  
  2. public:  
  3.     vector<vector<int> > threeSum(vector<int> &num) {    
  4.         vector<vector<int> >  result;    
  5.   
  6.         sort(num.begin(), num.end());    
  7.           
  8.         /*Call 2 sum*/  
  9.         for(int i = 0; i < num.size(); i++){    
  10.             if(i > 0 && num[i] == num[i-1]) continue;    
  11.             twoSum(num, result, i);  
  12.         }   
  13.         return result;    
  14.     }  
  15.       
  16.     /*2 sum algorithm. different from the other one is that the other one return index not value*/  
  17.     void twoSum(vector<int> &num, vector<vector<int>> &res, int targetIndex) {  
  18.         /*starting from targetIndex + 1 is because the numbers before have been used*/  
  19.             int i = targetIndex + 1;     
  20.             int j = num.size()-1;    
  21.               
  22.             while(i < j){    
  23.                 if(num[targetIndex] + num[i] + num[j] < 0)   i++;    
  24.                 else if(num[targetIndex] + num[i] + num[j] > 0)   j--;    
  25.                 else{    
  26.                     vector<int> v;    
  27.                     v.push_back(num[targetIndex]);    
  28.                     v.push_back(num[i]);    
  29.                     v.push_back(num[j]);    
  30.                     res.push_back(v);    
  31.                     i++; j--;    
  32.                     while(i < num.size() && num[i]==num[i - 1]) i++;    
  33.                     while(j >= 0 && num[j] == num[j + 1]) j--;    
  34.                 }    
  35.             }  
  36.               
  37.     }  
  38. };  

0 0
原创粉丝点击