LeetCode 15 三數之和

2021-09-10 11:07:55 字數 1099 閱讀 1225

給定乙個包含 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)

:"""

:type nums: list[int]

:rtype: list[list[int]]

"""nums_hash =

result =

list()

for num in nums:

nums_hash[num]

= nums_hash.get(num,0)

+1if0

in nums_hash and nums_hash[0]

>=3:

[0,0

,0])

neg =

list

(filter

(lambda x: x <

0, nums_hash)

) pos =

list

(filter

(lambda x: x>=

0, nums_hash)

)for i in neg:

for j in pos:

dif =

0- i - j

if dif in nums_hash:

if dif in

(i, j)

and nums_hash[dif]

>=2:

[i, j, dif]

)if dif < i or dif > j:

[i, j, dif]

)return result

LeetCode 15 三數之和

15.給定乙個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組 方法一,個人解法正確,但是效率太低,時間複雜度o n 3 時間超時,無法提交至leetcode public s...

leetcode 15 三數之和

給定乙個包含 n 個整數的陣列nums,判斷nums中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組。例如,給定陣列 nums 1,0,1,2,1,4 滿足要求的三元組集合為 1,0,1 1,1,2 class solutio...

leetcode15 三數之和

給定乙個包含 n 個整數的陣列nums,判斷nums中是否存在三個元素 a,b,c 使得 a b c 0 找出所有滿足條件且不重複的三元組。注意 答案中不可以包含重複的三元組。例如,給定陣列 nums 1,0,1,2,1,4 滿足要求的三元組集合為 1,0,1 1,1,2 先找兩數之和,然後再用un...