給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
例如, 給定陣列 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[[-1, 0, 1],
[-1, -1, 2]
]分析排序
雙指標避免重複統計
class
solution
:def
threesum
(self, nums: list[
int])-
> list[list[
int]]:
result =
# 排序
nums.sort(
)
n =len(nums)
for i in
range
(n):
left = i +
1 right = n -
1# 避免重複統計
if i >
0and nums[i]
== nums[i -1]
:continue
while left < right:
sum= nums[i]
+ nums[left]
+ nums[right]
ifsum==0
:[nums[i]
, nums[left]
, nums[right]])
left +=
1 right -=
1# 避免重複統計
while nums[left]
== nums[left -1]
and left < right:
left +=
1while nums[right]
== nums[right +1]
and left < right:
right -=
1elif
sum<0:
left +=
1else
: right -=
1return result
15 三數之和
給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組。例如,給定陣列 nums 1,0,1,2,1,4 滿足要求的三元組集合為 1,0,1 1,1,2 最首先想到的是來三層...
15 三數之和
給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組。有兩種寫法 第一種耗時久,但容易解讀 class solution if nums.length 3 else if ...
15 三數之和
給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組。例如,給定陣列 nums 1,0,1,2,1,4 滿足要求的三元組集合為 1,0,1 1,1,2 定義兩個指標,分別指...