题目原文:
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] ]
题意分析:
给出一个数组,从中寻找三个数字并满足其和为零的条件,放回所有可能的组合情况。
首先对传入的数组进行排序,然后从左到右遍历每个元素(零元素左侧),将其作为哨兵。在哨兵元素右侧查找两个其和与哨兵元素的绝对值相等的元素。
除三个元素都为零的情况外,必定至少有一个元素为负数。
解题代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//先对容器进行排序,从左到右便利每个元素a,从其右侧找到两个符合条件的元素b和c,满足 -a = b+c
//对b和c的查找可在线性时间内完成,因此问题的解决时间为O(n^2)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> vRet;
vector<int> vElem;
int nSum = 0;
if (nums.size()<3)
{
return vRet;
}
sort(nums.begin(),nums.end());
for (int i =0; i<nums.size()-2; i++)
{
nSum = -nums[i];
int nHead = i+1;
int nTail = nums.size()-1;
//上一次循环已经查找过
if (i>0 && nums[i] == nums[i-1])
{
continue;
}
//其右侧不可能有组合使其和为零,退出查找
if (nSum < 0)
{
break;
}
//比较完所有可能性
while (nHead < nTail)
{
if (nHead > i+1 && nums[nHead] == nums[nHead-1])
{
nHead++;
continue;
}
if (nSum < nums[nHead] + nums[nTail])
{
nTail--;
}
else if (nSum > nums[nHead] + nums[nTail])
{
nHead++;
}
else
{
vElem.clear();
vElem.push_back(-nSum);
vElem.push_back(nums[nHead]);
vElem.push_back(nums[nTail]);
nHead++;
vRet.push_back(vElem);
}
}
}
return vRet;
}
};
//int main()
//{
// int nArr[] = {7,-1,14,-12,-8,7,2,-15,8,8,-8,-14,-4,-5,7,9,11,-4,-15,-6,1,-14,4,3,10,-5,2,1,6,11,2,-2,-5,-7,-6,2,-15,11,-6,8,-4,2,1,-1,4,-6,-15,1,5,-15,10,14,9,-8,-6,4,-6,11,12,-15,7,-1,-9,9,-1,0,-4,-1,-12,-2,14,-9,7,0,-3,-4,1,-2,12,14,-10,0,5,14,-1,14,3,8,10,-8,8,-5,-2,6,-11,12,13,-7,-12,8,6,-13,14,-2,-5,-11,1,3,-6};
// int nLeng = sizeof(nArr)/sizeof(int);
// vector<int> vInput(nArr,nArr+nLeng);
//
// vector<vector<int>> vout = Solution().threeSum(vInput);
// int n = vout.size();
// cout<<n<<endl;
// system("pause");
// return 1;
//}