class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for(int first = 0; first < n; ++first) {
if(first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int target = -nums[first];
int second = first + 1;
int third = n -1;
while(second < third){
if(second > first + 1 && nums[second] == nums[second - 1]){
second++;
continue;
}
if(third < n - 1 && nums[third + 1] == nums[third]){
third--;
continue;
}
int tmp = nums[third] + nums[second];
if(tmp > target){
third--;
}else if(tmp < target){
second++;
}else{
List<Integer> tmp_list = new ArrayList<>();
tmp_list.add(nums[first]);
tmp_list.add(nums[second]);
tmp_list.add(nums[third]);
ans.add(tmp_list);
second++;
}
}
}
return ans;
}
}