Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
3
Indexable
Never
import java.util.*;

class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = input.nextInt();
        }
        Solution solution = new Solution();
        List<List<Integer>> result = solution.threeSum(nums);
        for (int i = 0; i < result.size(); i++) {
            for (int j = 0; j < result.get(i).size(); j++) {
                System.out.print(result.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans=new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            if (i > 0 && nums[i] == nums[i-1]) continue; // skip duplicates
            int st=i+1,en=nums.length-1;
            while(st<en){
                int s=nums[i]+nums[st]+nums[en];
                if(s==0){
                    ans.add(Arrays.asList(nums[i], nums[st], nums[en]));
                    st++;
                    en--;
                    while (st < en && nums[st] == nums[st-1]) st++; // skip duplicates
                    while (st < en && nums[en] == nums[en+1]) en--; // skip duplicates
                }else if(s<0){
                    st++;
                }else{
                    en--;
                }
            }
        }
        return ans;
    }
}