思路:
- 特判,对于数组长度 n,如果数组为 null或者数组长度小于 3,返回 []。
- 对数组进行排序。
- 遍历排序后数组:
若 nums[i]>0:因为已经排序好,所以后面不可能有三个数加和等于 0,直接返回结果。
对于重复元素:跳过,避免出现重复解
令左指针 L=i+1,右指针 R=n-1,当 L<R时,执行循环:
当 nums[i]+nums[L]+nums[R]==0,执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 L,R 移到下一位置,寻找新的解
若和大于 0,说明 nums[R] 太大,R 左移
若和小于 0,说明 nums[L]太小,L 右移
这里只需要注重两处去重即可,想法就是固定一位数字,移动两位数字这样
代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int N = nums.size();
vector<vector<int> > res;
for (int i = 0; i < N - 2; ++i) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1;
int r = N - 1;
while (l < r) {
int s = nums[i] + nums[l] + nums[r];
if (s > 0) {
--r;
} else if (s < 0) {
++l;
} else {
res.push_back({nums[i], nums[l], nums[r]});
while (l < r && nums[l] == nums[++l]);
while (l < r && nums[r] == nums[--r]);
}
}
}
return res;
}
};