Java 18 lines solution


  • 1
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> l = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            int a = nums[i];
            for (int j = i + 1, k = nums.length - 1; j < k; j++) {
                int b = nums[j], c = nums[k];
                while (j < k && (c = nums[k]) + a + b > 0)
                    k--;
                if (a + b + c == 0)
                    l.add(Arrays.asList(a, b, c));
                while (j < nums.length - 2 && nums[j] == nums[j + 1]) 
                    j++;
            }   
            while (i < nums.length - 2 && nums[i] == nums[i + 1]) 
                i++;
        }   
        return l;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.