給你一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例:
給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:[ [-1, 0, 1], [-1, -1, 2]]來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/3sum/
Link:https://leetcode.com/problems/3sum/
雙指針O(N^2)
之前的Two Sum, 是有哈希和雙指針兩種解法的。
但是,對於本題,不能包含重複答案。對於這樣的限制。排序更容易去重複, 需選擇合適的代表, 所以採用雙指針的方案
題目要求a + b + c = k, 只要遍歷一遍數組,賦值給a,剩下的就變成了2數之和問題。即b + c = k - a(k = 0)
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]:
res = [] nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]: continue
a = nums[i] left = i + 1 right = len(nums) - 1
while left < right:
if nums[left] + nums[right] == -a: res.append([a, nums[left], nums[right]])
while (left < right and nums[left] == nums[left + 1]): left += 1
while (left < right and nums[right] == nums[right - 1]): right -= 1
left += 1 right -= 1 elif nums[left] + nums[right] > -a: right -= 1 else: left += 1
return res--End--