1. 程式人生 > 其它 >【經典面試題】給定一個由 n 個整陣列成的陣列 list,在 list 中是否有元素 a, b, c 這樣的 a + b + c = 0?找出陣列中所有唯一的三元組,得出總和等於0 注:得到的解集不能包含重複的三元組。

【經典面試題】給定一個由 n 個整陣列成的陣列 list,在 list 中是否有元素 a, b, c 這樣的 a + b + c = 0?找出陣列中所有唯一的三元組,得出總和等於0 注:得到的解集不能包含重複的三元組。

# conding:utf8
# author:mylittlegoblin

import pytest


class Three_list():
def three_list(self, nums):
res = []
nums.sort() # 首先機進行大小排序
for index_x in range(0, len(nums) - 2): # len(nums)-2 避免重複計算
if nums[index_x] > 0: # 如果第一個數大於零的話 後面的數相加肯定大於0 無需計算
break
if index_x > 0 and nums[index_x] == nums[index_x - 1]: # 如果相鄰的兩個資料相等則退出運算
break
index_y, index_z = index_x + 1, len(nums) - 1
while index_y < index_z:
sum_nums = nums[index_x] + nums[index_y] + nums[index_z]
if sum_nums < 0: # 總和小於零時把中間數右移以增大數值
index_y += 1
elif sum_nums > 0: # 總和大於零時把尾數左移以減少數值
index_z -= 1
else:
res.append([nums[index_x], nums[index_y], nums[index_z]]) # 符合條件的計入res中
while index_y < index_z and nums[index_y] == nums[index_y + 1]: # 避免重複資料計算
index_y += 1
while index_y < index_z and nums[index_z] == nums[index_z - 1]:
index_z -= 1
index_y += 1
index_z -= 1
if res == []:
return "該陣列無解"
else:
return res


def test_three_list():
test_list = [-1, 0, 1, 2, -1, -4]
third_list = Three_list()
print(third_list.three_list(test_list))