提示
LintCode中的相关算法题实现代码,可以在我的GitHub中下载。
题目需求
给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
样例
如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)
解题思路
使用指针法,一个指针指向最底端,一个指针指向最高端,中间的指针两个指针徘徊,先将数组排序,这样就可以在以后的选择过程中,省去重复元组的判断。
1.如果三个指针之和等于目标值,先移动中间的指针,排除掉重复元素;然后就移动低端指针,排除掉低端重复值;最后移动高端指针,也是去掉重复元素;如果中间指针大于等于高端指针,重置条件;否则,如果中间大于最低指针,则移动中间指针;否则最后重置中间指针。
2.如果三元素之和大于0,那么将重置中间指针,然后将高端指针减1;
3.否则移动中间指针,或者重置条件。
实现代码
class Solution {
public:
/**
* @param numbers: Give an array numbers of n integer
* @return: Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int>> threeSum(vector<int> &numbers) {
vector<vector<int>> result;
int length=numbers.size();
if(length<3) return result;
sort(numbers.begin(),numbers.end());
int low=0;
int high=length-1;
int p=1;
vector<int> tmp;
while(low<high)
{
if(p<high&&numbers[low]+numbers[high]+numbers[p]==0)
{
vector<int> tmp{numbers[low],numbers[p],numbers[high]};
result.push_back(tmp);
while(p<length-1)
{
if(numbers[p]==numbers[p+1]) p++;
else break;
}
while(low<length-1)
{
if(numbers[low]==numbers[low+1]) low++;
else break;
}
while(high>0)
{
if(numbers[high]==numbers[high-1]) high--;
else break;
}
if(p>=high-1)
{
low++;
p=low+1;
high=length-1;
}
else if(p>low) p++;
else
p=low+1;
}
else if(p<high&&numbers[low]+numbers[high]+numbers[p]>0)
{
p=low+1;
high--;
}
else
{
if(p>=high-1)
{
low++;
p=low+1;
high=length-1;
}
else p++;
}
}
return result;
}
};