給定一個包含 n 個整數的數組 S,判斷是否存在三個元素 a, b, c 使得 a + b + c = 0?找出所有滿足條件且不重複的三元組。
(a, b, c) 必須按非遞減順序排列(即 a ≤ b ≤ c)輸入:S = [-1, 0, 1, 2, -1, -4]
輸出:[[-1, 0, 1], [-1, -1, 2]]
這道題可以轉化為「兩數之和」的變體。關鍵在於處理重複元素——若不加剪枝,LeetCode 會判定超時(TLE)。
O(N log N)。O(N²),總複雜度 O(N²)。nums[i] == nums[i-1] 則 continue。class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> res;
if (n < 3) return res;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; ++i) {
if (i > 0 && nums[i] == nums[i-1]) continue; // 剪枝
int l = i + 1, r = n - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
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;
} else if (sum < 0) ++l;
else --r;
}
}
return res;
}
};
Runtime: 68 ms,通過所有測試用例。