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
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
**注意:**答案中不可以包含重复的三元组 。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { if(!nums || nums.lengt<3){ return [] }; let result = [];//存放结果 let second; let last; nums.sort((a,b)=>a-b);//排序 for(let i=0;i<nums.length;i++){ if(nums[i]>0){ break; } if(i>0 && nums[i] === nums[i-1]){//去重 continue; } second = i+1; last = nums.length-1; while(second<last){ if(nums[i]+nums[second]+nums[last] == 0){ result.push([nums[i],nums[second],nums[last]]); while(second<last && nums[second] === nums[second+1]){//去重 second++; } while(second<last && nums[last] === nums[last-1]){//去重 last--; } second++; last--; }else if(nums[i]+nums[second]+nums[last] < 0){ while(second<last && nums[second] === nums[second+1]){//去重 second++; } second++; }else{ while(second<last && nums[last] === nums[last-1]){//去重 last--; } last--; } } } return result; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
三数之和
一、题目详情
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
**注意:**答案中不可以包含重复的三元组 。
示例:
二、解题思路
三、代码实现
The text was updated successfully, but these errors were encountered: