提示
与两数之和只差了一个数字,可以将第一个数作为target,便转为两数之和
思路——双向指针
-
如何使双向指针有效运作?——对数组进行排序
-
如何将三数之和转为两数之和?——以第一个元素为target进行寻找
-
target如何去重选择?避免second错过与first相同的值,每次取重复中的第一个数字
-
如何避免得到重复的答案?——second third同时移动 跳过相同的元素
代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());//使用双向指针需要对数组进行排序
int n = nums.size();
//遍历数组 寻找出多个不同的first作为target
for (int first = 0; first < n - 1; first++) {
//这里要是重复就取重复中的第一个数字
if (first > 0 && nums[first] == nums[first - 1])
continue;
else {
//将第一个元素看成target
int target = -nums[first];
//将 三数之和 转换为 两数之和 问题
int second = first + 1, third = n - 1;
while (second < third) {
if (nums[second] + nums[third] == target)
{
ans.push_back({ nums[first],nums[second],nums[third] });
//如果找到了 second third就同时移动 并跳过相同元素
int second_val = nums[second];
int third_val = nums[third];
do { second++; }
while (second < third && nums[second] == second_val);
do { third--; }
while (second < third && nums[third] == third_val);
}
else if (nums[second] + nums[third] < target)
second++;
else
third--;
}
}
}
return ans;
}
};