1.Description:
?
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.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
2.Ideas:
?
這道題需要從一個(gè)列表中選出所有滿足和為0的三元組,且要求去重,最簡(jiǎn)單的思路就是暴力的3層循環(huán),這樣肯定會(huì)超時(shí)。我們可以簡(jiǎn)單的進(jìn)行分析,三個(gè)數(shù)的和為零,可以先確定一個(gè)數(shù),然后再確定另外兩個(gè)數(shù),使另外兩個(gè)數(shù)的和為第一個(gè)確定數(shù)的相反數(shù),這樣就可以將O(n^3)轉(zhuǎn)為O(n^2)。我們可以讓第一個(gè)確定的數(shù)為一個(gè)不大于0的數(shù),而且,因?yàn)樽羁斓呐判蛩惴ǖ臅r(shí)間復(fù)雜度是O(nlogn)
3.Code:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
L = []
nums.sort()
length = len(nums)
if(length<3):
return L
for i in range(length-2):
if(nums[i]>0):#三個(gè)大于0的數(shù)之和不會(huì)是0
break
if(i>0 and nums[i]==nums[i-1]):#去掉重復(fù)的情況
continue
target = -nums[i]
left = i+1
right = length-1
while left < right:
if(nums[left]+nums[right]==target):
temp = []
temp.append(nums[i])
temp.append(nums[left])
temp.append(nums[right])
L.append(temp)
left+=1
right-=1
while left
< right:
left += 1
if nums[left] > nums[left - 1]: break
else:
while left < right:
right -= 1
if nums[right] < nums[right + 1]: break
return L
4.Result:
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
