-
-
Notifications
You must be signed in to change notification settings - Fork 487
Expand file tree
/
Copy paththree_sum.dart
More file actions
46 lines (39 loc) · 1005 Bytes
/
three_sum.dart
File metadata and controls
46 lines (39 loc) · 1005 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//Leetcode problem no. 15: https://leetcode.com/problems/3sum/description/
//Time Complexity: O(N^2)
//Space Complexity: O(1)
//Input: A list of integers
//Output: A list of lists containing all those integers whose sum end up to 0
import 'package:test/test.dart';
import '../sort/heap_Sort.dart';
List<List<int>> threeSum(List<int> l){
List<List<int>> ans=[];
sort(l);
for(int i=0; i<l.length; ++i){
if(i!=0 && l[i]==l[i-1]) continue;
int j=i+1, k=l.length-1;
while(j<k){
int sum=l[i]+l[j]+l[k];
if(sum<0) j++;
else if(sum>0) k--;
else{
ans.add([l[i], l[j], l[k]]);
j++;
k--;
while(j<k && l[j]==l[j-1]) j++;
while(j<k && l[k]==l[k+1]) k--;
}
}
}
return ans;
}
void main(){
test('test 1', () {
expect(threeSum([-1,0,1,2,-1,-4]), [[-1,-1,2],[-1,0,1]]);
});
test('test 2', () {
expect(threeSum([0, 1, 1]), []);
});
test('test 3', () {
expect(threeSum([0, 0, 0]), [[0,0,0]]);
});
}