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
No description provided.
The text was updated successfully, but these errors were encountered:
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
这是一道经典的双指针题!
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { const res = [], len = nums.length; nums.sort((a, b) => a - b); for (let i = 0; i < len - 2; i++){ if (nums[i] > 0){ return res; } if (nums[i] === nums[i - 1]){ continue; } let left = i + 1; let right = len - 1; while (left < right){ let sum = nums[i] + nums[left] + nums[right]; if (sum > 0){ right--; }else if (sum < 0){ left++; }else{ res.push([nums[i], nums[left], nums[right]]); while (left < right && nums[left] === nums[left + 1]){ left++; } while (left <right && nums[right] === nums[right - 1]){ right--; } // 经过上述两个while,去重了相同的元素,但我们需要从下一个元素开始 left++; right--; } } } return res; };
Sorry, something went wrong.
No branches or pull requests
No description provided.
The text was updated successfully, but these errors were encountered: