0015. 3Sum (M)

3Sum (M)

题目

Given an array nums of n integers, are there elements a, b, c in nums such that a + 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

题意

找到所有和为0的三元组,但不允许重复。

思路

如果只要求找到满足的三元组:先对数组nums排序,固定最小的数为i,在[i + 1, nums.length - 1]区间中运用two pointers方法找到j、k,使得j

问题在于去除重复的三元组:遇到新nums[i]值时,应当先将该值按照上述方法判断处理后,再去除后面所有与它相同的值,因为可能会出现 (-1, -1, 2)、(0, 0, 0) 这样满足条件的组,如果先去除重复的值,再用剩下的最后一个值去判断求和,会遗漏这些含有重复值的对。


代码实现

Java

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

        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1, k = nums.length - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (j > i + 1 && nums[j] == nums[j - 1] || sum < 0) {
                    j++;
                } else if (k < nums.length - 1 && nums[k] == nums[k + 1] || sum > 0) {
                    k--;
                } else {
                    List temp = new ArrayList<>();
                    temp.add(nums[i]);
                    temp.add(nums[j++]);
                    temp.add(nums[k--]);
                    list.add(temp);
                }
            }
        }

        return list;
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  let res = []
  nums.sort((a, b) => a - b)
  for (let i = 0; i < nums.length; i++) {
    if (i > 0 && nums[i] == nums[i - 1]) {
      continue
    }
    let target = -nums[i]
    let left = i + 1,
      right = nums.length - 1
    while (left < right) {
      if ((left > i + 1 && nums[left] == nums[left - 1]) || nums[left] + nums[right] < target) {
        left++
      } else if ((right < nums.length - 1 && nums[right] == nums[right + 1]) || nums[left] + nums[right] > target) {
        right--
      } else {
        res.push([nums[i], nums[left++], nums[right--]])
      }
    }
  }
  return res
}

你可能感兴趣的:(0015. 3Sum (M))