Find the three elements that sum to zero from a set of n real numbers
def three_sum(*arrys):
nums, result, i = sorted(arrys),[],0
# 将三个元素分别赋值,顺带排序(具体原理很深奥,但使用起来非常简洁)
while i < len(nums) -2:
# i遍历所有元素(除了最后两个以外),从list中index为0开始
j,k = i+1, len(nums)-1
# j从list中index为1的元素开始遍历,k为尾部开始。两个指针j和k分别向中间靠拢
while j<k:
if nums[i] + nums[j] + nums[k] < 0: #j从左至右遍历
j += 1
elif nums[i] + nums[j] + nums[k] > 0: #k从右至左遍历
k -= 1
else:
result.append([nums[i],nums[j],nums[k]])
# 把三项之和为0的数列插入result列表尾部(但是需要优化算法,去掉重复元素)
j, k = j + 1, k - 1
while j < k and nums[j] == nums[j - 1]:
# j和k同时变化,如果不一起变化的话,容易多一次无用的比较
j += 1
while j < k and nums[k] == nums[k + 1]:
k -= 1
i += 1
return result
------------------
#示例如下
three_sum(-25, -10, -7, -3,-4,-6, 2, 4, 8, 10)
[[-10, 2, 8], [-7, -3, 10], [-6, -4, 10], [-6, 2, 4]]
import datetime #引用时间模块
starttime = datetime.datetime.now() #记录初始时间
def three_sum(*arrys):
nums, result, i = sorted(arrys),[],0
while i < len(nums) -2:
j,k = i+1, len(nums)-1
while j<k:
if nums[i] + nums[j] + nums[k] < 0:
j += 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
else:
result.append([nums[i],nums[j],nums[k]])
j, k = j + 1, k - 1
while j < k and nums[j] == nums[j - 1]:
j += 1
while j < k and nums[k] == nums[k + 1]:
k -= 1
i += 1
return result
three_sum(-25, -10, -7, -3,-4,-6, 2, 4, 8, 10)
endtime = datetime.datetime.now()
# 记录结束时间
print((endtime - starttime))
# 算法运行时间为0:00:00.000388
0:00:00.000388 #运行时间
如下为此题(使用类class)编写的代码及其英文解释
代码及其英文解释