題目
給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例
給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合爲:[[-1, 0, 1],[-1, -1, 2]]
參考leetcode[1]兩數之和的解法:先排序再使用對撞指針。再考慮剪枝操作。
三數之和的解法:
先對數組進行排序
剪枝:
剪枝優化,就是當遍歷到正數的時候就break,爲啥呢,因爲我們的數組現在是有序的了,如果第一個要fix的數就是正數了,那麼後面的數字就都是正數,就永遠不會出現和爲0的情況了。
然後我們還要加上重複就跳過的處理,處理方法是從第二個數開始,如果和前面的數字相等,就跳過,因爲我們不想把相同的數字fix兩次。
對於遍歷到的數,用0減去這個fix的數得到一個target,然後只需要再之後找到兩個數之和等於target即可。我們使用對撞指針。
代碼如下:注意代碼塊中的 這一句
if i>0 and nums[i]==nums[i-1]:
這是個坑,一定注意加i>0這個條件。也即nums[0]=0的這種情況,不執行continue操作,當i>0時continue纔有效。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
if len(nums)<3:
return result
for i in range(len(nums)-2):
if nums[i] >0:
break
if i>0 and nums[i]==nums[i-1]:
continue
l = i+1
r = len(nums)-1
while l<r:
if nums[l]+nums[r]==-nums[i]:
result.append([nums[l],nums[r],nums[i]])
while l<r and nums[l]==nums[l+1]:
l +=1
while l<r and nums[r]==nums[r-1]:
r -=1
l+=1
r-=1
elif nums[l]+nums[r]<-nums[i]:
l+=1
else:
r -=1
return result