LC15 三數之和
1 題目
給你一個整數數組 nums ,判斷是否存在三元組 [nums[i], nums[j], nums[k]] 滿足 i != j、i != k 且 j != k ,同時還滿足 nums[i] + nums[j] + nums[k] == 0 。請你返回所有和為 0 且不重復的三元組。
注意:答案中不可以包含重復的三元組。
示例 1:
輸入:nums = [-1,0,1,2,-1,-4]
輸出:[[-1,-1,2],[-1,0,1]]
解釋:
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 。
不同的三元組是 [-1,0,1] 和 [-1,-1,2] 。
注意,輸出的順序和三元組的順序并不重要。
示例 2:
輸入:nums = [0,1,1]
輸出:[]
解釋:唯一可能的三元組和不為 0 。
示例 3:
輸入:nums = [0,0,0]
輸出:[[0,0,0]]
解釋:唯一可能的三元組和為 0 。
提示:
3 <= nums.length <= 3000-105 <= nums[i] <= 105
2 解答
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(0 , len(nums)-2 , 1):
if ((nums[i] == nums[i-1]) and (i > 0)):
continue
index_left = i + 1
index_right = len(nums) - 1
while (index_left < index_right):
s = nums[i]+nums[index_left] +nums[index_right]
if s>0:
index_right-=1
elif s<0:
index_left+=1
else:
res.append([nums[i], nums[index_left] , nums[index_right]])
index_left +=1
while (index_left<index_right and nums[index_left]==nums[index_left-1]):
index_left+=1
index_right -= 1
while (index_left<index_right and nums[index_right] == nums[index_right+1]):
index_right-=1
return res

浙公網安備 33010602011771號