题解
双指针
感觉就是对题目的深度理解,首先遍历a 那么就是找 b + c = -a 的情况。首先不能进行暴力解决,所以要有一定的简化,b 代表左指针,c 代表右指针,对于去掉重复的,需要先对数组从小到大排序,看到重复的直接过掉即可,这样的话,b 从左向右变大,c 从右向左遍历,保持平衡,最后当两个数同一位置的时候那么遍历结束。
先打了一遍官方代码,感觉逻辑还是有些混乱的,建议看第二份代码,还是比较清晰的。
代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> ans;
//1.先排序
sort(nums.begin(),nums.end());
//枚举
for(int first = 0; first < n; first++){
if(first > 0 &&nums[first] == nums[first - 1]){
continue;//如果下面这个数和之前那个数一致,那么就会跳过这个数,因为不能有重复的
}
int third = n - 1;//对应c,即右指针,c从右向左进行搜索
int target = -nums[first];//-a
//枚举b
for(int second = first + 1; second < third; ++second){
if(second > first + 1 && nums[second] == nums[second - 1]){//b不能和之前的数相同
continue;
}
while(second < third && nums[second] + nums[third] > target){
third--;
}
if(second == third){
break;
}
if(nums[second] + nums[third] == target){//b + c = -a
ans.push_back({nums[first],nums[second],nums[third]});
}
}
}
return ans;
}
};
第二份
啊啊啊啊。真的好多细节,,,,不想动脑
代码如下:比较清晰的
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> ans;
//1.先排序
sort(nums.begin(),nums.end());
//枚举
int left,right = n - 1;
for(int a = 0; a < n; a++){
if(nums[a] > 0)break;//直接没有满足条件的
if(a > 0 && nums[a] == nums[a - 1])continue;
left = a + 1;
right = n - 1;
while(left < right){
int sum = nums[a] + nums[left] + nums[right];
if(sum == 0){
ans.push_back({nums[a],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 if(sum > 0)right--;
}
}
return ans;
}
};