刷题第二天~~~
【题目】
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]
]
这道题目的思路很简单,先将数组排序,接着按排好的顺序进行匹配,第一轮循环的任务是确定首个数字,接着便可以确定另外两个数字的和的大小,第二轮循环就是在首个数字和数组末尾之间的元素中找出剩余两个数。
【c++代码】
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
int size = nums.size() - 1;
//第一轮循环只需要搜索小于0的数即可
for (int i = 0;i < size && nums[i] <= 0;)
{
int num_need = -nums[i];
//第二个数字和第三个数字的下标
int first = i + 1, second = size;
while (first < second)
{
int sum = nums[first] + nums[second];
if (num_need > sum)
{
first++;
} else if (num_need < sum)
{
second--;
} else
{
vector<int> rel;
rel.push_back(nums[i]);
rel.push_back(nums[first]);
rel.push_back(nums[second]);
res.push_back(rel);
//防止第二个数重复
while (first < second && nums[++first] == nums[first - 1]);
//防止第三个数重复
while (first < second && nums[--second] == nums[second + 1]);
}
}
//防止第一个数重复
while (i < size - 1 && nums[++i] == nums[i - 1]);
if (i == size - 1)
{
i++;
}
}
return res;
};
};