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] ]
分析
寻找数组中的3个数使得其和为0, a+ b+ c = 0。这道题可以分解成,在数组寻找两个数a,b,使得其和等于-c, a+b = -c。
首先需要对数组进行排序,这样可以比较快的找到两个数。然后从头至尾遍历数组, i start from 0 to nums.size(), 为了防止结果重复,需要在[i, nums.size())中找到这两个数,这样只要nums[i]之前已经查找过了,之后的结果中就不会再出现nums[i]了。
需要考虑一种情况,nums[i] = nums[i-1]时,同样会造成结果的重复,因此遍历时,当遇到这种情况直接跳过即可。
在寻找a,b两个数的过程中,同样需要防止结果重复。举例来说,nums排好序之后是这样的
nums:[-4, -1, 0, 1, 1]
nums[1] = -1
nums[2] + nums[3] = - nums[1]
nums[2] + nums[4] = - nums[1]
所以在寻找a,b的时候如果发现已经存在了相同的两元数组时,需要跳过。
Code
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
std::sort (nums.begin(), nums.end());
int length = nums.size();
vector<vector<int>> res;
int prevInt = INT_MAX;
for (int i =0; i < length; i ++)
{
if (prevInt == nums[i])
{
continue;
}
prevInt = nums[i];
vector<vector<int>> twoSumRes = twoSum(nums, i+1, 0 - nums[i]);
for (int j = 0; j < twoSumRes.size(); j ++)
{
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(twoSumRes[j][0]);
tmp.push_back(twoSumRes[j][1]);
res.push_back(tmp);
}
}
return res;
}
vector<vector<int>> twoSum(vector<int>& nums, int start, int sum)
{
int length = nums.size();
int i = start;
int j = length - 1;
vector<vector<int>> res;
vector<int> tmp;
tmp.push_back(INT_MAX);
tmp.push_back(INT_MAX);
while (i < j)
{
if (nums[i] + nums[j] == sum && nums[i] != tmp[0] && nums[j] != tmp[1])
{
tmp[0] = nums[i];
tmp[1] = nums[j];
res.push_back(tmp);
}
else if (nums[i] + nums[j] > sum)
{
j --;
continue;
}
else if (nums[i] + nums[j] < sum)
{
i ++;
continue;
}
}
return res;
}
};
运行效率
Runtime: 128 ms, faster than 52.46% of C++ online submissions for 3Sum.
Memory Usage: 24.4 MB, less than 18.54% of C++ online submissions for3Sum.
总体来看运行效率并没有很高。空间的原因可能在于twoSum中使用了vector做暂存,这样会增加copy和内存的使用,直接在threeSum中做遍历和查找,这样会对空间有比较大的节约,但是可读性不好。