我的想法是把三个变为两个
1±1等于零即可
先遍历两个元素
例如第一个和第二个
然后在剩下的里面去遍历,是否有为二者之和的相反数的
如果有将这三个数添加到数组里面
如果没有找第一个和第三个
然后遍历完一遍后
找二个和第三个开始
这样时间复杂度大概是n^3
肯定是不太行的
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
// 首先对数组进行排序
Arrays.sort(nums);
// 遍历数组
for (int i = 0; i < nums.length - 2; i++) {
// 跳过重复的数字
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
// 使用双指针查找满足条件的三元组
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.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 (sum < 0) {
left++;
} else {
right--;
}
}
}
return res;
}
}