Simple Java Solution - Without using Hash/Set


  • 22
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        for(int i = 0; i < nums.length-2; i++) {
            if(i > 0 && (nums[i] == nums[i-1])) continue; // avoid duplicates
            for(int j = i+1, k = nums.length-1; j<k;) {
                if(nums[i] + nums[j] + nums[k] == 0) {
                    list.add(Arrays.asList(nums[i],nums[j],nums[k]));
                    j++;k--;
                    while((j < k) && (nums[j] == nums[j-1]))j++;// avoid duplicates
                    while((j < k) && (nums[k] == nums[k+1]))k--;// avoid duplicates
                }else if(nums[i] + nums[j] + nums[k] > 0) k--;
                else j++;
            }
        }
        return list;
    }

  • 9

    The idea here is to sort the array first. Then for each element(i), have two pointers at the beginning(j), and end(k). Check if 3sum == 0.

    To avoid duplicates, if any of the next number is same, just skip it. That is, if nums[i] is same as previous, skip it. Similarly for nums[j] and nums[k]


  • 0
    S

    it will take less time if we write sum=nums[i] + nums[j] + nums[k] at first.


  • 0
    T

    that's a great thinking!


Log in to reply
 

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