网站首页 > 技术文章 正文
原始编程试题如下:
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
第一次编写链接如下:
https://www.toutiao.com/article/7484270109578560027/
第二次编写链接如下:
https://www.toutiao.com/article/7484802365191684646/
经过再三思考,发现了第二次编码中影响效率的地方:
- 重复结果检查效率低:使用了 if result not in resultList 来检查结果是否已经存在,这种方法的时间复杂度是 O(n),对于较大的数据集来说效率很低。
- 频繁的列表操作:每次找到一个三元组时,都会创建一个新的列表 result,并将其添加到 resultList 中,这会增加额外的开销。
问题点找到了,解决的办法其实就很简单了,于是,在第二次的基础上,写出了最终的代码:
可编辑代码如下:
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
resultList = []
numlen = len(nums)
nums.sort()
for i in range(0, numlen-2):
start, end = i+1, numlen-1
# 跳过重复的数
if (i > 0 and nums[i] == nums[i - 1]) :
continue
# 优化点1:提前终止条件
if nums[i] + nums[i + 1] + nums[i + 2] > 0:
break
if nums[i] + nums[numlen - 2] + nums[numlen - 1] < 0:
continue
while(start < end):
if (nums[i] + nums[start]+ nums[end] == 0):
# 优化点2:直接将list加入到返回列表中
resultList.append([nums[i], nums[start], nums[end]])
start += 1
end -= 1
while (start < end) and nums[start] == nums[start-1]:
start += 1
while (start < end) and nums[end] == nums[end+1]:
end -= 1
elif (nums[i] + nums[start] + nums[end] > 0):
end -= 1
else:
start += 1
return resultList
执行结果如下:
猜你喜欢
- 2025-04-27 Python 机器学习 线性回归的损失和优化
- 2025-04-27 Python3 多线程:优化并发执行,提升效率(37)
- 2025-04-27 优化数据处理效率:Python数据清洗的实例详解
- 2025-04-27 9个可以显著优化代码的Python内置装饰器
- 2025-04-27 300分钟Python入门第21天 - 小明的购物清单优化
- 2025-04-27 Scalene:Python CPU+GPU+内存分析器,具有AI驱动的优化建议
- 2025-04-27 使用Python实现智能物流系统优化与路径规划
- 2025-04-27 并发的艺术:如何用 asyncio.Semaphore 优化你的 Python 程序
- 2025-04-27 掌握 Python 中的代码分析 —— 性能分析和优化工具综合指南
- 2025-04-27 Python性能优化:为什么“while 1”比“while True”更快?
- 263℃Python短文,Python中的嵌套条件语句(六)
- 263℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 256℃Python实现字符串小写转大写并写入文件
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 116℃原来2025是完美的平方年,一起探索六种平方的算吧
- 96℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 89℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)