public class Solution15 {
public static List<List<Integer>> threeSum(int[] nums) {
int j=0,k=0;
Arrays.sort(nums);
List<List<Integer>> tol=new ArrayList<>();
for(int i=0;i<nums.length;i++)
{
while(i>0&&i<nums.length&&nums[i]==nums[i-1])
{
i++;
}
j=i+1;
k=nums.length-1;
while(j<k)
{
List<Integer> triplets=new ArrayList<>();
if(nums[i]+nums[j]+nums[k]==0)
{
triplets.add(nums[i]);
triplets.add(nums[j]);
triplets.add(nums[k]);
tol.add(triplets);
j++;
k--;
while(j<k&&nums[j]==nums[j-1])
{
j++;
}
while(k > j && nums[k] == nums[k+1])
k --;
}
else if(nums[i]+nums[j]+nums[k]>0)
{
k--;
while(k > j && nums[k] == nums[k+1])
k--;
}
else
{
j++;
while(j<k&&nums[j]==nums[j-1])
{
j++;
}
}
}
}
return tol;
}