Skip to content

Commit 885208e

Browse files
committed
15. 3Sum
1 parent c17404a commit 885208e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

problem46/main.dart

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
2+
3+
//15. 3Sum
4+
5+
void main(List<String> args) {
6+
print(threeSum([-1,0,1,2,-1,-4]));
7+
print(threeSum([0,1,1]));
8+
print(threeSum([-2,0,0,2,2]));
9+
}
10+
threeSum(List<int> list){
11+
list.sort();
12+
var resultList=[];
13+
for(int i=0;i<list.length-2;i++){
14+
15+
var left=i+1;
16+
var right=list.length-1;
17+
if(i > 0 && list[i] == list[i-1]){
18+
continue;
19+
}
20+
21+
while(left<right){
22+
int sum=list[i]+list[left]+list[right];
23+
if(sum>0){
24+
right --;
25+
}
26+
if(sum<0){
27+
left++;
28+
}
29+
if(sum==0){
30+
var temp=[];
31+
temp.add(list[i]);
32+
temp.add(list[left]);
33+
temp.add(list[right]);
34+
resultList.add(temp);
35+
left ++;
36+
right --;
37+
while(left<list.length&& list[left]==list[left-1]){
38+
left++;
39+
}
40+
while(right>i &&list[right]==list[right+1]){
41+
right --;
42+
}
43+
}
44+
}
45+
}
46+
47+
return resultList;
48+
}

0 commit comments

Comments
 (0)