暴力解法import java. util. * ; public class _15_ThreeSum1 { public List < List < Integer > > threeSum ( int [ ] nums) { if ( nums == null || nums. length < 3 ) return new ArrayList < > ( ) ; Set < List < Integer > > res = new HashSet < > ( ) ; Arrays . sort ( nums) ; for ( int i = 0 ; i < nums. length; i++ ) { for ( int j = i + 1 ; j < nums. length; j++ ) { for ( int k = j + 1 ; k < nums. length; k++ ) { if ( nums[ i] + nums[ j] + nums[ k] == 0 ) { res. add ( Arrays . asList ( nums[ i] , nums[ j] , nums[ k] ) ) ; } } } } return new ArrayList < > ( res) ; } public static void main ( String [ ] args) { int [ ] nums = { - 1 , 0 , 1 , 2 , - 1 , - 4 } ; System . out. println ( new _15_ThreeSum1 ( ) . threeSum ( nums) ) ; }
}
import java. util. * ; public class _15_ThreeSum2 { public List < List < Integer > > threeSum ( int [ ] nums) { if ( nums == null || nums. length < 3 ) return new ArrayList < > ( ) ; Set < List < Integer > > res = new HashSet < > ( ) ; Arrays . sort ( nums) ; for ( int i = 0 ; i < nums. length; i++ ) { int target = - nums[ i] ; int left = i + 1 ; int right = nums. length - 1 ; while ( left < right) { int sum = nums[ left] + nums[ right] ; if ( sum == target) { res. add ( Arrays . asList ( nums[ i] , nums[ left] , nums[ right] ) ) ; left++ ; right-- ; } else if ( sum < target) { left++ ; } else { right-- ; } } } return new ArrayList < > ( res) ; } public static void main ( String [ ] args) { int [ ] nums = { - 1 , 0 , 1 , 2 , - 1 , - 4 } ; System . out. println ( new _15_ThreeSum2 ( ) . threeSum ( nums) ) ; }
}
import java. util. ArrayList ;
import java. util. Arrays ;
import java. util. List ; public class _15_ThreeSum3 { public List < List < Integer > > threeSum ( int [ ] nums) { if ( nums == null || nums. length < 3 ) return new ArrayList < > ( ) ; List < List < Integer > > res = new ArrayList < > ( ) ; Arrays . sort ( nums) ; for ( int i = 0 ; i < nums. length - 2 ; i++ ) { if ( i > 0 && nums[ i] == nums[ i - 1 ] ) continue ; int target = - nums[ i] ; int left = i + 1 ; int right = nums. length - 1 ; while ( left < right) { int sum = nums[ left] + nums[ right] ; if ( sum == target) { res. add ( Arrays . asList ( nums[ i] , nums[ left] , nums[ right] ) ) ; while ( left < right && nums[ left] == nums[ ++ left] ) ; while ( left < right && nums[ right] == nums[ -- right] ) ; } else if ( sum < target) { left++ ; } else { right-- ; } } } return res; } public static void main ( String [ ] args) { int [ ] nums = { - 1 , 0 , 1 , 2 , - 1 , - 4 } ; System . out. println ( new _15_ThreeSum3 ( ) . threeSum ( nums) ) ; }
}