```
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
Arrays.sort(num); // first sort the array
if(num.length>0){
int former = num[0];
if(former>0 || num.length<3){ // the length is less than 3 or the first element>0 return
return result;
}
Set<ArrayList<Integer>> Test_dup = new HashSet<>(); // avoid duplicate
for(int i=1;i<num.length;i++){
int sum = former + num[i];
if(sum<0){
int index = Arrays.binarySearch(num,-sum); // try to find the index using binarySearch
if(index>=0){
ArrayList<Integer> elements = new ArrayList<>();
elements.add(former);
elements.add(num[i]);
elements.add(num[index]);
if(!Test_dup.contains(elements)){
result.add(elements);
}
Test_dup.add(elements);
}
}
former = num[i];
}
}
return result;
}
```

}