3 Sum Zero

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is: (-1, 0, 1) (-1, -1, 2)

class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(ArrayList<Integer> nums) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        Collections.sort(nums);
        for (int i = 0; i + 2 < nums.size(); i++) {
            if (i > 0 && nums.get(i).compareTo(nums.get(i - 1)) == 0) {
                continue;
            }
            int j = i + 1, k = nums.size() - 1;
            long target = (-1L) * (long) nums.get(i);
            // System.out.println(target);
            while (j < k) {
                if ((long) nums.get(j) + (long) nums.get(k) == target) {
                    ArrayList<Integer> temp = new ArrayList<>();
                    temp.addAll(Arrays.asList(nums.get(i), nums.get(j), nums.get(k)));
                    Collections.sort(temp);
                    res.add(temp);
                    j++;
                    k--;
                    while (j < k && nums.get(j).compareTo(nums.get(j - 1)) == 0)
                        j++; // skip same result
                    while (j < k && nums.get(k).compareTo(nums.get(k + 1)) == 0)
                        k--; // skip same result
                } else if (nums.get(j) + nums.get(k) > target) {
                    k--;
                } else {
                    j++;
                }
            }
        }
        return res;
    }
}

Last updated