题目:
Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路:
经典的二分之路的开启题目。强烈推荐大家按照题目的推荐系列做题,会把这一思路的题目思考的很透彻。
代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> tri;
if (nums.size() < 1)
return tri;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++)
{
if (i == 0 || (i > 0 && nums[i] != nums[i - 1]))
{
int sum = 0 - nums[i];
int low = i + 1;
int high = nums.size() - 1;
while (low < high)
{
int rest = nums[low] + nums[high];
if (rest == sum)
{
tri.push_back(vector<int>{nums[i], nums[low], nums[high]});
while (low < nums.size() - 1 && nums[low] == nums[low + 1])
low++;
while (high > 0 && nums[high] == nums[high - 1])
high--;
low++;
high--;
}
else if (rest < sum)
low++;
else high--;
}
}
}
return tri;
}
};