knakul853

Untitled

Jun 13th, 2020
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     vector<vector<int>> threeSum(vector<int>& nums) {
  7.        
  8.         int n = (int)nums.size();
  9.         vector<vector<int>>ans;
  10.        
  11.         sort(nums.begin(), nums.end());
  12.        
  13.         for( int i=0;i<n;i++)
  14.         {
  15.             int l = i+1;
  16.             int r = n-1;
  17.             int target = -nums[i];
  18.            
  19.             while( l < r )
  20.             {
  21.                 int sm = (nums[l] + nums[r]);
  22.                
  23.                 if( sm > target ) r--;
  24.                 else if( sm < target ) l++;
  25.                
  26.                 else{
  27.                     ans.push_back({nums[l], nums[r], nums[i]});
  28.                    
  29.                     int skipLeft =nums[l];
  30.                     int skipRight = nums[r];
  31.                    
  32.                     while( l < r && skipLeft == nums[l] )l++;
  33.                     while( l < r && skipRight == nums[r] )r--;
  34.                 }
  35.             }
  36.            
  37.             while(i+1 < n && nums[i] == nums[i+1])i++;
  38.         }
  39.        
  40.         return ans;
  41.     }
  42. };
Add Comment
Please, Sign In to add comment