問題描述: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. 給定一個長度爲n的數字串,是否存在三個元素a,b,c使得a+b+c=0,找出所有不同的元素組。不能包含重複的元素組。
樣例:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路:最粗暴的解法是 n³ 的複雜度,每層循環選中一個元素,判斷和是否爲0。
有一個複雜度爲 n² 的算法:先將所有元素從小到大排好序,然後選取一個元素 i,另外兩個元素 j,k 初始時在 i 之後的數組的兩端,然後移動 j,k 的位置使得三者的和爲0(其中 j 只向右移,k只向左移)。C++實現代碼如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>result;
if(nums.size()<=2) return result;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-2;++i){
if(nums[i]>0) break;
if(i>0&&nums[i-1]==nums[i]) continue;
for(int j=i+1,k=nums.size()-1;j<k;){
int a=nums[j],b=nums[k];
int value=nums[i]+a+b;
if(value==0){
vector<int>temp;
temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(nums[k]);
result.push_back(temp);
while(b==nums[--k]);
while(a==nums[++j]);
}
else if(value>0){
--k;
}
else{
++j;
}
}
}
return result;
}
};