15. 3Sum#

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.

The distinct triplets are [-1,0,1] and [-1,-1,2].
 1public List<List<Integer>> threeSum(int[] nums) {
 2  List<List<Integer>> result = new ArrayList<>();
 3  Arrays.sort(nums);
 4
 5  for (int i = 0; i < nums.length - 2; i++) {
 6    // if nums[i] and nums[i-1] are same continue
 7    if (i > 0 && nums[i] == nums[i - 1]) {
 8      continue;
 9    }
10
11    int l = i + 1;
12    int r = nums.length - 1;
13
14    while (l < r) {
15      int sum = nums[i] + nums[l] + nums[r];
16
17      if (sum < 0) {
18        // need to increase
19        l++;
20      } else if (sum > 0) {
21        // need to decrease
22        r--;
23      } else {
24        List<Integer> triplet = Arrays.asList(nums[i], nums[l++], nums[r--]);
25        result.add(triplet);
26
27        // if next left value is same as current right ignore
28        while (l < r && nums[l] == nums[l - 1]) {
29          l++;
30        }
31
32        // if next right value is same as current right ignore
33        while (l < r && nums[r] == nums[r + 1]) {
34          r--;
35        }
36      }
37    }
38  }
39  return result;
40}