1
+ namespace LeetCodeSolutions . TwoPointers
2
+ {
3
+ public class ThreeSumSolution
4
+ {
5
+ public IList < IList < int > > ThreeSum ( int [ ] nums )
6
+ {
7
+ IList < IList < int > > returnValue = new List < IList < int > > ( ) ;
8
+ Array . Sort ( nums ) ;
9
+
10
+ for ( int i = 0 ; i < nums . Length ; i ++ )
11
+ {
12
+ if ( i > 0 && nums [ i ] == nums [ i - 1 ] )
13
+ continue ;
14
+
15
+ int left = i + 1 ;
16
+ int right = nums . Length - 1 ;
17
+
18
+ while ( left < right )
19
+ {
20
+ int threeSum = nums [ i ] + nums [ left ] + nums [ right ] ;
21
+
22
+ if ( threeSum > 0 )
23
+ right -- ;
24
+ else if ( threeSum < 0 )
25
+ left ++ ;
26
+ else
27
+ {
28
+ List < int > currentList =
29
+ [
30
+ nums [ i ] ,
31
+ nums [ left ] ,
32
+ nums [ right ]
33
+ ] ;
34
+ returnValue . Add ( currentList ) ;
35
+ left ++ ;
36
+ while ( nums [ left ] == nums [ left - 1 ] && left < right )
37
+ left ++ ;
38
+ }
39
+ }
40
+ }
41
+
42
+ return returnValue ;
43
+ }
44
+
45
+ [ Test ( Description = "https://leetcode.com/problems/3sum/" ) ]
46
+ [ Category ( "Medium" ) ]
47
+ [ Category ( "LeetCode" ) ]
48
+ [ Category ( "3Sum" ) ]
49
+ [ TestCaseSource ( nameof ( Input ) ) ]
50
+ [ Category ( "TwoPointers" ) ]
51
+ [ Category ( "TopInterview" ) ]
52
+ public void Test1 ( ( IList < IList < int > > Output , int [ ] Input ) item )
53
+ {
54
+ var response = ThreeSum ( item . Input ) ;
55
+ Assert . That ( response , Is . EqualTo ( item . Output ) ) ;
56
+ }
57
+
58
+ public static IEnumerable < ( IList < IList < int > > Output , int [ ] Input ) > Input =>
59
+ new List < ( IList < IList < int > > Output , int [ ] Input ) > ( )
60
+ {
61
+ ( new List < IList < int > > ( )
62
+ {
63
+ new List < int > ( ) { - 1 , - 1 , 2 } ,
64
+ new List < int > ( ) { - 1 , 0 , 1 }
65
+ } , [ - 1 , 0 , 1 , 2 , - 1 , - 4 ] ) ,
66
+ } ;
67
+ }
68
+ }
0 commit comments