题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/de3e7d8db7d792335ba149f8be21afbd.png)
代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums.length < 3) return ans;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int left = i + 1, right = nums.length - 1,sum = -nums[i];
if (i > 0 && nums[i] == nums[i - 1]) continue;
while (left < right) {
if (nums[left] + nums[right] == sum) {
ans.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
}
else if (nums[left] + nums[right] > sum) right--;
else left++;
}
}return ans;
}
}
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b1e602ef6c9f1db8752900dae6eb8a16.png)