剑指 Offer II 007. 数组中和为 0 的三个数
剑指 Offer II 007. 数组中和为 0 的三个数
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
for(int i = 0;i<n-2;i++){
if(i!=0&&nums[i]==nums[i-1]) continue;
int target = -nums[i];
int l = i+1, r = n-1;
while(l<r){
if(nums[l]+nums[r]==target){
res.add(Arrays.asList(nums[i],nums[l],nums[r]));
int tmp = nums[l];
while(l<r&&nums[l]==tmp) l++;
tmp = nums[r];
while(l<r&&nums[r]==tmp) r--;
}else if(nums[l]+nums[r]<target){
int tmp1 = nums[l];
while(l<r&&nums[l]==tmp1) l++;
}else{
int tmp2 = nums[r];
while(l<r&&nums[r]==tmp2) r--;
}
}
}
return res;
}
}