### 解题思路
按照leetcode官方题解的写法,采用双指针进行优化
- 三重循环枚举每一个数字。
- 第一个优化,为了不产生重复的res结果,首先对 n u m s nums nums数组进行一个排序, i = 0 , j = i + 1 , k = j + 1 i=0,j=i+1,k=j+1 i=0,j=i+1,k=j+1这个样子的一直往后枚举,枚举的时候需要去重,具体的说就是说每一个数字比如2在 i i i这一层循环里只枚举一次。
- f i r s t first first+ s e c o n d second second+ t h i r d third third=0对于这个,我们得到 t h i r d = − ( f i r s t + s e c o n d ) third=-(first+second) third=−(first+second),当 s e c o n d second second朝增大的方向走的时候, t h i r d third third是朝着变小的方向走的,于是 s e c o n d second second和 t h i r d third third这边可以使用双指针进行优化。
- 具体的优化方法看上面的leetcode的官方题解。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n=nums.size();
vector<vector<int>>ans;
if(n<3){
return ans;
}
// vector<int>tmp(3);
sort(nums.begin(),nums.end());
for(int first=0;first<n;first++){
// 去重
if(first>0&&nums[first]==nums[first-1]){
continue;
}
int target=-(nums[first]);
int third=n-1;
for(int second=first+1;second<n;second++){
// 去重
if(second>first+1&&nums[second]==nums[second-1]){
continue;
}
while(second<third&&nums[second]+nums[third]>target){
third--;
}
if(second==third){
break;
}
if(nums[second]+nums[third]==target){
ans.push_back({nums[first],nums[second],nums[third]});
}
}
}
return ans;
}
};