10000 new solution · dev-ik/leetcode-typescript@f30ea45 · GitHub
[go: up one dir, main page]

Skip to content

Commit f30ea45

Browse files
committed
new solution
1 parent f7954bb commit f30ea45

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

018. 4Sum/index.test.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { fourSum } from './index';
2+
3+
describe('fourSum', () => {
4+
const testCases = [
5+
{
6+
name: 'Case 1',
7+
input: { nums: [1, 0, -1, 0, -2, 2], target: 0 },
8+
expected: [
9+
[-2, -1, 1, 2],
10+
[-2, 0, 0, 2],
11+
[-1, 0, 0, 1],
12+
],
13+
},
14+
{
15+
name: 'Case 2',
16+
input: { nums: [2, 2, 2, 2, 2], target: 8 },
17+
expected: [[2, 2, 2, 2]],
18+
},
19+
{
20+
name: 'Case 3',
21+
input: { nums: [-2, -1, -1, 1, 1, 2, 2], target: 0 },
22+
expected: [
23+
[-2, -1, 1, 2],
24+
[-1, -1, 1, 1],
25+
],
26+
},
27+
];
28+
29+
for (const testCase of testCases) {
30+
test(testCase.name, () => {
31+
expect(fourSum(testCase.input.nums, testCase.input.target)).toEqual(
32+
testCase.expected,
33+
);
34+
});
35+
}
36+
});

018. 4Sum/index.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Description:
2+
// Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
3+
//
4+
// 0 <= a, b, c, d < n
5+
// a, b, c, and d are distinct.
6+
// nums[a] + nums[b] + nums[c] + nums[d] == target
7+
//
8+
// You may return the answer in any order.
9+
10+
// Constraints:
11+
// 1 <= nums.length <= 200
12+
// -109 <= nums[i] <= 109
13+
// -109 <= target <= 109
14+
15+
export const fourSum = (nums: number[], target: number): number[][] => {
16+
nums.sort((a, b) => a - b);
17+
const l = nums.length;
18+
const res: number[][] = [];
19+
20+
for (let i = 0; i < l - 3; i++) {
21+
if (i > 0 && nums[i] === nums[i - 1]) {
22+
continue;
23+
}
24+
25+
for (let j = i + 1; j < l - 2; j++) {
26+
if (j > i + 1 && nums[j] === nums[j - 1]) {
27+
continue;
28+
}
29+
let left = j + 1;
30+
let right = l - 1;
31+
while (left < right) {
32+
const sum = nums[i] + nums[j] + nums[left] + nums[right];
33+
34+
if (sum === target) {
35+
res.push([nums[i], nums[j], nums[left], nums[right]]);
36+
left++;
37+
right--;
38+
while (nums[left] === nums[left - 1]) {
39+
left++;
40+
}
41+
while (nums[right] === nums[right + 1]) {
42+
right--;
43+
}
44+
} else if (sum < target) {
45+
left++;
46+
} else {
47+
right--;
48+
}
49+
}
50+
}
51+
}
52+
53+
return res;
54+
};

0 commit comments

Comments
 (0)
0