【原文】:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
【题意】:
找出一个列表中所有和为零的三元组。要求求出的三元组中没有重复。
注意点:
- 三元组中的数字要按增序排列(a<=b<=c)
- 结果集中没有重复的三元组
例子:
输入: nums=[-1, 0, 1, 2, -1, -4]
输出: [[-1, -1, 2], [-1, 0, 1]]
【思路】:
思路1:(1)3个数字相加等于0,一般来说分为:负+正+正 和 负+正+正(把为0的情况归到为正)。
(2)需要先对数组进行排序。
(3)将数组分成两部分:负数和正数:假定三个断点:a(最左端),b(中间,正数(或者0)开始),c(最右端)。当a+b+c>0时,b不动,c向左移动一个位置;当a+b+c<0时,c不动,b向右移动一个位置;当a+b+c=0时,记录下来,并且b,c置初始位置,a向右移动一个。
(4)这种做法的时间复杂度O(n*n)
思路2:其实不需要将列表进行分段(正负区分),直接做循环即可,如下图:

在指针b和c向前移动时进行判断:即是指针b向前移动还是指针c向后移动。如果满足条件,则记录下3个指针所指向的元素。
具体代码实现如下:
import random
# 1.产生指定个数和指定范围的无重复的随机数:
count = int(input("请输入要产生的随机数的个数:"))
tmpArray = []
tmpArray = random.sample(range(-10, 10),count)
# 2.给数组元素排序
finalList = []
tmpArray.sort()
nowLength = len(tmpArray)
# 3.查找满足条件的元素
for i in range(0, nowLength):
left = i + 1
right = nowLength - 1
while((left <= right)):
if (tmpArray[i] + tmpArray[left] + tmpArray[right] > 0):
right = right - 1
elif(tmpArray[i] + tmpArray[left] + tmpArray[right] < 0):
left = left + 1
else:
# 保存数据
list = []
list.append(tmpArray[left])
list.append(tmpArray[right])
list.append(tmpArray[i])
if(list not in finalList):
finalList.append(list)
right = right - 1
left = left + 1
else:
print(finalList)
举例输入列表:[-10, -7, -3, -1, 0, 1, 3, 4, 6, 8]
输出结果为:[[4, 6, -10], [-1, 8, -7], [1, 6, -7], [3, 4, -7], [-1, 4, -3], [0, 3, -3], [0, 1, -1]]