-
Notifications
You must be signed in to change notification settings - Fork 1
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
15. 3Sum #209
Labels
Comments
Solution
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
const result = [];
const sortedNums = [...nums].sort((a, b) => a - b);
for (let i = 0; i < sortedNums.length - 2; i++) {
if (sortedNums[i] > 0) {
break;
}
if (i > 0 && sortedNums[i] === sortedNums[i - 1]) {
continue;
}
let left = i + 1;
let right = sortedNums.length - 1;
while (left < right) {
if (left > i + 1 && sortedNums[left] === sortedNums[left - 1]) {
left++;
continue;
}
if (
right < sortedNums.length - 1
&& sortedNums[right] === sortedNums[right + 1]
) {
right--;
continue;
}
if (sortedNums[i] + sortedNums[left] + sortedNums[right] < 0) {
left++;
} else if (sortedNums[i] + sortedNums[left] + sortedNums[right] > 0) {
right--;
} else {
result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
left++;
right--;
}
}
}
return result;
};
function threeSum(nums: number[]): number[][] {
const result: number[][] = [];
const sortedNums = [...nums].sort((a, b) => a - b);
for (let i = 0; i < sortedNums.length - 2; i++) {
if (sortedNums[i] > 0) {
break;
}
if (i > 0 && sortedNums[i] === sortedNums[i - 1]) {
continue;
}
let left = i + 1;
let right = sortedNums.length - 1;
while (left < right) {
if (left > i + 1 && sortedNums[left] === sortedNums[left - 1]) {
left++;
continue;
}
if (
right < sortedNums.length - 1
&& sortedNums[right] === sortedNums[right + 1]
) {
right--;
continue;
}
if (sortedNums[i] + sortedNums[left] + sortedNums[right] < 0) {
left++;
} else if (sortedNums[i] + sortedNums[left] + sortedNums[right] > 0) {
right--;
} else {
result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
left++;
right--;
}
}
}
return result;
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
15. 3Sum
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
Example
Note
The text was updated successfully, but these errors were encountered: