Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf30ea45

Browse files
committed
new solution
1 parentf7954bb commitf30ea45

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+
consttestCases=[
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(consttestCaseoftestCases){
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+
exportconstfourSum=(nums:number[],target:number):number[][]=>{
16+
nums.sort((a,b)=>a-b);
17+
constl=nums.length;
18+
constres:number[][]=[];
19+
20+
for(leti=0;i<l-3;i++){
21+
if(i>0&&nums[i]===nums[i-1]){
22+
continue;
23+
}
24+
25+
for(letj=i+1;j<l-2;j++){
26+
if(j>i+1&&nums[j]===nums[j-1]){
27+
continue;
28+
}
29+
letleft=j+1;
30+
letright=l-1;
31+
while(left<right){
32+
constsum=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+
}elseif(sum<target){
45+
left++;
46+
}else{
47+
right--;
48+
}
49+
}
50+
}
51+
}
52+
53+
returnres;
54+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp