import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        int l = num.length;
        if(l < 3){
            return res;
        }
        Arrays.sort(num);
        for(int i = 0;i < l-2; i++){
            if(i != 0 && num[i] == num[i-1]){
                continue;
            }
            int left = i+1;
            int right = l-1;
            int target = 0-num[i];
            while(left < right){
                if(num[left] + num[right] == target){
                    ArrayList<Integer> temp = new ArrayList<>();
                    temp.add(num[i]);
                    temp.add(num[left]);
                    temp.add(num[right]);
                    res.add(temp);
                    while(left+1 < right && num[left] == num[left+1]){
                        left++;
                    }
                    while(left < right-1 && num[right-1] == num[right]){
                        right--;
                    }
                    left++;
                    right--;
                }else if(num[left] + num[right]>target){
                    right--;
                }else{
                    left++;
                }
            }
        }
        return res;
    }
}