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]
]
解題思路
這道題是之前的Two Sum題的升級版,不同的是Two Sum要求返回的是數組的下標,而本題要求返回的是數組元素本身。大體思路如下:
- 對數組進行排序
- 遍歷數組,將每次遍歷變成一個Two Sum的問題,注意需要跳過重復的數字
- 由于數據已經排序,解決Two Sum問題的時候,可以直接使用兩個下標從數組頭尾分別開始掃描。假設數組為nums, 頭尾下標分別為beg和end, 若nums[beg] + nums[end] > target,則end--, 否則beg++。
具體代碼如下所示:
class Solution
{
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
int target = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(nums[i] > 0) break; //如果第一個數字>0, 直接返回。
if(i > 0 && nums[i] == nums[i-1]) continue; //數字重復,直接跳出本次循環
int l = i+1 , r= nums.size() - 1;
target = 0 - nums[i];
while(l < r)
{
if(nums[l] + nums[r] > target)
r--;
else if(nums[l] + nums[r] < target)
l++;
else{
res.push_back({nums[i],nums[l],nums[r]});
while(l < r && nums[l] == nums[l + 1]) l++;
while(l < r && nums[r] == nums[r - 1]) r--;
l++; r--;
}
}
}
return res;
}
}
思路二:
根據網上大神的解法,可以采用set不能包含重復項的特點來防止重復項的產生。具體代碼如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
set<vector<int>> res;
int target = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(nums[i] > 0) break;
int l = i+1 , r= nums.size() - 1;
target = 0 - nums[i];
while(l < r)
{
if(nums[l] + nums[r] > target)
r--;
else if(nums[l] + nums[r] < target)
l++;
else{
res.insert({nums[i],nums[l],nums[r]});
l++; r--;
}
}
}
return vector<vector<int>>(res.begin(),res.end());
}
};