zentan66 / daily-coding

日常手写算法,编程题
0 stars 0 forks source link

LeetCode-三数之和「数组」 #2

Open zentan66 opened 3 years ago

zentan66 commented 3 years ago

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

zentan66 commented 3 years ago

编码实现

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  const res = []
  const len = nums.length
  nums.sort((a, b) => a - b)
  for (let i = 0; i < len; i++) {
    if (nums[i] > 0) break
    if (i > 0 && nums[i] === nums[i - 1]) continue
    let L = i + 1
    let R = len - 1
    while (L < R) {
      const t = nums[i] + nums[L] + nums[R]
      if (t === 0) {
        res.push([nums[i], nums[L], nums[R]])
        while (L < R && nums[L] == nums[L + 1]) L++ // 去重 例如 [-2, 0, 0, 2]
        while (L < R && nums[R] == nums[R - 1]) R-- // 去重 
        L++
        R--
      } else if (t < 0) {
        L++
      } else {
        R--
      }
    }
  }
  return res
}

思路

  1. 先对数组进行排序
  2. 然后先固定一个元素,如果该元素大于0,那么合肯定大于0,可以跳过循环
  3. 固定元素后,用元素后续集合使用双指针【需要注意的是要过滤重复的情况】