排序+双指针:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>(); // 存储结果的列表
Arrays.sort(nums); // 对数组进行排序
for (int i = 0; i < nums.length - 2; i++) { // 遍历数组,注意到倒数第二个元素为止
if (i != 0 && nums[i] == nums[i - 1]) {
continue; // 当前元素与前一个元素相等,跳过,避免重复
}
int t = nums[i]; // 当前元素
int left = i + 1; // 左指针
int right = nums.length - 1; // 右指针
while (left < right) {
int p = nums[left] + nums[right] + t; // 当前三个元素的和
if (p != 0) {
if (p > 0) {
right--; // 和大于0,将右指针左移
} else {
left++; // 和小于0,将左指针右移
}
} else {
// 和为0,找到满足条件的三元组
// 首先后两个数种可能存在重复的数,因此要跳过重复的数
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
//然后 将结果添加到结果集中,并移动指针
List<Integer> list = new ArrayList<>();
list.add(t);
list.add(nums[left]);
list.add(nums[right]);
result.add(list);
left++;
right--;
}
}
}
return result;
}
}