LeetCode 15.

Tags:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums); //nlogn
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        int current = 0;
        for (int i=0; i<nums.length; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue;
            int left = i+1, right = nums.length-1;
            while (left < right) {
                current = nums[i] + nums[left] + nums[right];
                if (current == 0) {
                    List<Integer> l = new ArrayList<>();
                    l.add(nums[i]);
                    l.add(nums[left]);
                    l.add(nums[right]);
                    result.add(l);
                    left++;
                    while (nums[left] == nums[left-1] && left<right){
                        left++;
                    }
                }else if (current < 0) {
                    left++;
                }else{
                    right--;
                }
            }
        }

        return result;
    }
}

Check out the description of this problem at LC 15.