題目
給你一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例:
給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合爲:
[
[-1, 0, 1],
[-1, -1, 2]
]
解題思路
排序 + 雙指針
本題的難點在於如何去除重複解。
算法流程:
- 特判,對於數組長度 n,如果數組爲 null 或者數組長度小於 3,返回 []。
- 對數組進行排序。
- 遍歷排序後數組:
- 若 nums[0]>0:因爲已經排序好,所以後面不可能有三個數加和等於 0,直接返回結果。
- 對於重複元素:跳過,避免出現重複解
- 令左指針 L=i+1,右指針 R=n−1,當 L<R時,執行循環:
- 當nums[i]+nums[L]+nums[R]==0,執行循環,判斷左界和右界是否和下一位置重複,去除重複解。並同時將 L,R 移到下一位置,尋找新的解
- 若和大於 0,說明 nums[R] 太大,R 左移
- 若和小於 0,說明 nums[L]太小,L 右移
複雜度分析
- 時間複雜度:O(n^2),數組排序 O(N \log N),遍歷數組 O(n),雙指針遍歷 O(n),總體 O(N \log N)+O(n)∗O(n),O(n ^2)
空間複雜度:O(1)
# Cpp
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
if(nums.size()<3) return ans;
sort(nums.begin(), nums.end());
if(nums[0]>0) return ans;
int i = 0;
while(i<nums.size()){
if(nums[i]>0) break; // 1樓網友指正,將這個if語句放這裏提前終止循環
int left = i+1, right = nums.size()-1;
while(left< right){
// 轉換爲long long避免加法過程中溢出
long long y = static_cast<long long>(nums[i]);
long long x = static_cast<long long>(nums[left]);
long long z = static_cast<long long>(nums[right]);
if(x + y >0-z)
right--;
else if(x + y <0-z)
left++;
else{
ans.push_back({nums[i], nums[left], nums[right]});
// 相同的left和right不應該再次出現,因此跳過
while(left<right&&nums[left]==nums[left+1])
left++;
while(left<right&&nums[right] == nums[right-1])
right--;
left++;
right--;
}
}
// 避免nums[i]作爲第一個數重複出現
while(i+1<nums.size()&&nums[i] == nums[i+1])
i++;
i++;
}
return ans;
}
};
# python3
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
res=[]
if(not nums or n<3):
return []
nums.sort()
res=[]
for i in range(n):
if(nums[i]>0):
return res
if(i>0 and nums[i]==nums[i-1]):
continue
L=i+1
R=n-1
while(L<R):
if(nums[i]+nums[L]+nums[R]==0):
res.append([nums[i],nums[L],nums[R]])
while(L<R and nums[L]==nums[L+1]):
L=L+1
while(L<R and nums[R]==nums[R-1]):
R=R-1
L=L+1
R=R-1
elif(nums[i]+nums[L]+nums[R]>0):
R=R-1
else:
L=L+1
return res
知識點
vector<vector> ans; //二維動態數組,默認爲空 []
[[-1,-1,2],[-1,0,1]]