public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num.length < 3)
return result;
Arrays.sort(num);
for(int i = 0; i < num.length - 2 ; i ++){
int first = num[i];
int j = i + 1;
int k = num.length - 1;
while(j < k){
int second = num[j];
int third = num[k];
if(second + third == -first){
ArrayList<Integer> solution = new ArrayList<Integer>();
solution.add(first);
solution.add(second);
solution.add(third);
result.add(solution);
while( ((j + 1) <= (num.length - 1)) && (num[j] == num[j + 1])) j ++;
j ++;
while( ((k - 1) >= 0) && (num[k] == num[k - 1])) k --;
k --;
}
else if(second + third < -first){
while( ((j + 1) <= (num.length - 1)) && (num[j] == num[j + 1])) j ++;
j ++;
}
else if(second + third > -first){
while( ((k - 1) >= 0) && (num[k] == num[k - 1])) k --;
k --;
}
}
while( ((i + 1) <= (num.length - 1)) && (num[i] == num[i + 1])) i ++;
j ++;
}
return result;
}
}