Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

三数之和 #6

Open
bWhirring opened this issue Dec 21, 2019 · 2 comments
Open

三数之和 #6

bWhirring opened this issue Dec 21, 2019 · 2 comments
Labels

Comments

@bWhirring
Copy link
Owner

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

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

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
@bWhirring
Copy link
Owner Author

bWhirring commented Dec 21, 2019

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
  const len = nums.length
  nums = nums.sort()
  let arr = new Set()

  for (let i = 0; i < len - 2; i++) {
    for (let j = i + 1; j < len - 1; j++) {
      const z = 0 - nums[i] - nums[j]
      if (nums.includes(z, j + 1)) {
        arr.add([nums[i], nums[j], z].toString())
      }
    }
  }
  return [...arr].map(v => v.split(',').map(n => Number(n)))
};

@bWhirring
Copy link
Owner Author

bWhirring commented Dec 21, 2019

var threeSum = function (nums) {
  let ret = new Set()
  nums = nums.sort((a, b) => a - b)
  const len = nums.length
  if (nums[0] > 0) return []

  for (let i = 0; i < len; i++) {
    let l = i + 1
    let r = len - 1
    while (l < r) {
      const sum = nums[i] + nums[l] + nums[r]
      if (sum === 0) {
        ret.add([nums[i], nums[l], nums[r]].toString())
        l++
        r--
      } else if (sum < 0) {
        l++
      } else if (sum > 0) {
        r--
      }
    }
  }

  return [...ret].map(v => v.split(',').map(n => Number(n)))
}

This was referenced Dec 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant