给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int len = nums.size();
vector<vector<int>> res;
if(len < 3)
{
return res;
}
sort(nums.begin(), nums.end());
const int target = 0;
for(int first = 0; first< len; first++)
{
if(first > 0 && nums[first] == nums[first-1])
{
continue;
}
int third = len-1;
for(int second = first +1; second < third; second++)
{
if(second > first+1 && nums[second] == nums[second - 1])
{
continue;
}
while(third > second && nums[first] + nums[second] + nums[third] > target)
{
third--;
}
if(second < third && (nums[first] + nums[second] + nums[third] == 0))
{
vector<int> tmp ;
tmp.push_back(nums[first]);
tmp.push_back(nums[second]);
tmp.push_back(nums[third]);
res.push_back(tmp);
}
}
}
return res;
}
};
原文:https://www.cnblogs.com/qiaozhoulin/p/14940569.html