题目描述:
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.
注意: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] ]
分析:
题意:给定一个包含n个整数的数组S,求所有的不重复三元组(a, b, c),使得a+b+c=0。
思路:此题采用双指针法。首先,我们对数组进行从小到大排序。我们用默认指针i遍历0→n-3代表查找的第一个数,指针left遍历i+1→right-1代表查找的第二个数,指针right遍历left+1→n-1代表查找的第三个数(i < left < right)。对于当前指针i,这里分三种情况讨论:①此时和等于0,则找到一组解,left右移、right左移(如果只移动一个指针,或者找到一组重复解、或者其和不等于0);②此时和小于0,则left右移;③此时和大于0,则right左移。
需要注意一点:每种情况处理之后,需要判断一下left和left-1对应值是否相等、right和right+1值是否相等。如果相等,则遇到了重复值,left继续右移、right继续左移,这样可以加快查找效率。对于指针i的循环,也采用相同的做法。
时间复杂度为O(nlogn)+O(n²)=O(n²)。
代码:
#include <bits/stdc++.h>
using namespace std;
// two points
class Solution {
private:
static int cmp(const int a, const int b){
return a < b;
}
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> ans;
// Exceptional Case:
if(n <= 2){
return ans;
}
// sort
sort(nums.begin(), nums.end(), cmp);
int left, right;
for(int i = 0; i <= n - 3;){
left = i + 1;
right = n - 1;
while(left < right){
int sum = nums[i] + nums[left] + nums[right];
if(sum == 0){
vector<int> res = {nums[i], nums[left], nums[right]};
ans.push_back(res);
left++;
right--;
// skip the same values
while(left < right && nums[left] == nums[left - 1]){
left++;
}
while(left < right && nums[right] == nums[right + 1]){
right--;
}
}
else if(sum < 0){
left++;
while(left < right && nums[left] == nums[left - 1]){
left++;
}
}
else if(sum > 0){
right--;
while(left < right && nums[right] == nums[right + 1]){
right--;
}
}
}
i++;
while(i <= n - 1 && nums[i] == nums[i - 1]){
i++;
}
}
return ans;
}
};