题目描述:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]解题思路:
首先对数组进行升序排序,然后遍历数组中的元素,固定当前遍历到的元素为第一个数,另外两个数一个从固定的数的后面一个开始,一个从数组的最后一个数开始,移动后两个数找到合适的三元组。
AC代码如下:
class Solution{
public:
vector<vector<int>> threeSum(vector<int>& nums){
vector<vector<int>> ans;
if (nums.size() < 3) return ans;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n; ++i){
if (i>0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现相同的三元组
int j = i + 1, k = n - 1;
while (j < k){
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0){
vector<int> tmp = { nums[i], nums[j], nums[k] };
ans.push_back(tmp);
while (++j < k && nums[j] == nums[j - 1]); //跳过重复的元素,避免结果中出现相同的三元组
while (j < --k && nums[k] == nums[k + 1]); //跳过重复的元素,避免结果中出现相同的三元组
}
else if(sum>0){
--k;
}
else{//sum<0
++j;
}
}
}
return ans;
}
};