
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int first = 0; first < n; first++){
if(first == 0 || nums[first] != nums[first - 1]){
int third = n - 1;
int target = -nums[first];
for(int second = first + 1; second < n; second++){
if(second == first + 1 || nums[second] != nums[second - 1]){
while(second < third && nums[second] + nums[third] > target)
--third;
if(second == third)
break;
if(nums[second] + nums[third] == target){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
res.add(list);
}
}
}
}
}
return res;
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int first = 0; first < n; first++){
if(first == 0 || nums[first] != nums[first - 1]){
int third = n - 1;
int target = -nums[first];
int second = first + 1;
while(second < third){
int sum = nums[second] + nums[third];
if(sum == target){
res.add(Arrays.asList(nums[first], nums[second], nums[third]));
while(second < third && nums[second] == nums[second + 1])
++second;
++second;
while(second < third && nums[third] == nums[third - 1])
--third;
--third;
}else if(sum < target){
second++;
}else{
third--;
}
}
}
}
return res;
}
}