15 3Sum

15. 3Sum

1. Question

Given an arraySofnintegers, are there elementsa,b,cinSsuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.

Note: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]
]

2. Implementation

(1) Two Pointers

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }

            int j = i + 1, k = nums.length - 1;

            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];

                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    ++j;
                    --k;

                    while (j < k && nums[j - 1] == nums[j]) ++j;
                    while (j < k && nums[k] == nums[k + 1]) --k;
                }
                else if (sum < 0) {
                    ++j;
                }
                else {
                    --k;
                }
            }
        }
        return res;
    }
}

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n^2)

Last updated