題目 : 15. 3Sum Medium
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
1.
這一題是3個數字相加=0,所以我們只要固定第1個數字,把它當成目標數,利用迴圈讓目標數從目標數之後的最左邊(l
)和最右邊(r
)的數根據3個數相加的結果來判斷要將l
往右走或是r
往左走來縮小範圍。
目標 l
-> <-r
-1 , -1 , 0 , 1 , 2 , 3
(當目標是-1的答案 : [-1,-1,2]、[-1,0,1])
line 5 : 為了加速找數字的時間和方便判別是否有遇過重複的數字,所以將nums用sorts()
進行排序
line 8 : 如果目前的num和前一個數字是一樣的,就直接continue下一個num,這是要避免掉重複的答案
line 11 : l
: 是目標數之後最左邊的index,r
: 是整個List中最右邊的index
line 13 : 如果threeSum
3個數字相加>0,代表數字太大,要將r
往左縮小範圍,讓threeSum
的數值變小
line 16 : 如果threeSum
3個數字相加<0,代表數字太小,要將l
往右縮小範圍,讓threeSum
的數值變大
line 18 : 如果threeSum
3個數字相加=0,代表得到答案!
line 19 : 答案append到res中
line 21 : 接下來可以看下一個l
,為了避免重複的答案,我們要判斷l
跟上一個l-1
是不是一樣,如果遇到一樣的情況l
再加1
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i, num in enumerate(nums):
if i > 0 and num == nums[i-1]:
continue
l, r = i+1, len(nums)-1
while l < r:
threeSum = num + nums[l] + nums[r]
if threeSum > 0 :
r -= 1
elif threeSum < 0 :
l += 1
else :
res.append([num,nums[l],nums[r]])
l += 1
while l < r and nums[l] == nums[l-1]:
l += 1
return res