class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
int n = nums.size();
for(int i = 0;i < n;i++){
while(i && i < n && nums[i] == nums[i-1]) i++;
int j = i + 1,k = n - 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(!sum){
vector<int>t = { nums[i],nums[j],nums[k] };
res.push_back(t);
j++; k--;
while(j < k && nums[j] == nums[j-1]) j++;
while(k > j && nums[k] == nums[k+1]) k--;
}
else if(sum < 0){
j++;
while(j < k && nums[j] == nums[j-1]) j++;
}
else{
k--;
while(k > j && nums[k] == nums[k+1]) k--;
}
}
}
return res;
}
};