Given an integer array nums, return all the triplets
[nums[i], nums[j], nums[k]]
such thati != j
,i != k
, andj != k
, andnums[i] + nums[j] + nums[k] == 0
.Notice that the solution set must not contain duplicate triplets.
class Solution:
def threeSum(self, nums):
# 巨慢
nums.sort()
res = []
for index1 in range(len(nums)):
index2, index3 = index1 + 1, len(nums) - 1
while index2 < index3:
temp = nums[index1] + nums[index2] + nums[index3]
# sum == 0
if temp == 0:
# 去重
if [nums[index1], nums[index2], nums[index3]] not in res:
res.append([nums[index1], nums[index2], nums[index3]])
index3 -= 1
elif temp > 0:
index3 -= 1
else:
index2 += 1
return res