We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Difficulty: 中等
Related Topics: 数组, 双指针, 排序
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
nums
[nums[i], nums[j], nums[k]]
i != j
i != k
j != k
nums[i] + nums[j] + nums[k] == 0
你返回所有和为 0 且不重复的三元组。
0
**注意:**答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]] 解释: 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 。 不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。 注意,输出的顺序和三元组的顺序并不重要。
示例 2:
输入:nums = [0,1,1] 输出:[] 解释:唯一可能的三元组和不为 0 。
示例 3:
输入:nums = [0,0,0] 输出:[[0,0,0]] 解释:唯一可能的三元组和为 0 。
提示:
3 <= nums.length <= 3000
Language: JavaScript
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { let ans = [] const len = nums.length if (nums === null || len < 3) return ans nums.sort((a, b) => a - b) for (let i = 0; i < nums.length; i++) { if (nums[0] > 0) break if (i > 0 && nums[i] === nums[i - 1]) continue let l = i + 1 let r = len - 1 while (l < r) { const sum = nums[i] + nums[l] + nums[r] if (sum === 0) { ans.push([nums[i], nums[l], nums[r]]) while(l < r && nums[l] === nums[l+1]) l++ while(l < r && nums[r] === nums[r-1]) r-- l++ r-- } else if (sum < 0) l++ else if (sum > 0) r-- } } return ans }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
15. 三数之和
Description
Difficulty: 中等
Related Topics: 数组, 双指针, 排序
给你一个整数数组
nums
,判断是否存在三元组[nums[i], nums[j], nums[k]]
满足i != j
、i != k
且j != k
,同时还满足nums[i] + nums[j] + nums[k] == 0
。请你返回所有和为
0
且不重复的三元组。**注意:**答案中不可以包含重复的三元组。
示例 1:
示例 2:
示例 3:
提示:
3 <= nums.length <= 3000
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: