package com. lsy. leetcodehot100 ;
import java. util. ArrayList ;
import java. util. Arrays ;
import java. util. List ;
public class _Hot6_三数之和 {
public static List < List < Integer > > threeSum ( int [ ] nums) {
Arrays . sort ( nums) ;
List < List < Integer > > result = new ArrayList < > ( ) ;
for ( int oneNum= 0 ; oneNum< nums. length- 2 ; oneNum++ ) {
if ( nums[ oneNum] > 0 ) break ;
if ( oneNum > 0 && oneNum == nums[ oneNum- 1 ] ) continue ;
int twoNum = oneNum + 1 ;
int threeNum = nums. length- 1 ;
while ( twoNum < threeNum) {
int sum = nums[ oneNum] + nums[ twoNum] + nums[ threeNum] ;
if ( sum < 0 ) {
while ( twoNum < threeNum && nums[ twoNum] == nums[ ++ twoNum] ) ;
} else if ( sum > 0 ) {
while ( twoNum < threeNum && nums[ threeNum] == nums[ -- threeNum] ) ;
} else {
List < Integer > resultList = Arrays . asList ( nums[ oneNum] , nums[ twoNum] , nums[ threeNum] ) ;
result. add ( resultList) ;
while ( twoNum < threeNum && nums[ twoNum] == nums[ ++ twoNum] ) ;
while ( twoNum < threeNum && nums[ threeNum] == nums[ -- threeNum] ) ;
}
}
}
return result;
}
public static void main ( String [ ] args) {
int [ ] nums= { - 1 , 0 , 1 , 2 , - 1 , - 4 } ;
List < List < Integer > > lists = threeSum ( nums) ;
for ( List < Integer > list : lists) {
System . out. println ( list) ;
}
}
}