python-3.x - Leetcode 3Sum 问题需要优化的 Python 解决方案
问题描述
这是问题陈述:
Given an array nums of n integers,
are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
笔记:
解决方案集不得包含重复的三元组。
例子:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[[-1, 0, 1],[-1, -1, 2]]
我现在正在解决 Leetcode 3Sum 问题,并得到以下代码的 Time Limit Exceeded 错误:
class Solution:
def threeSum(self, nums):
triplets=[]
nums.sort()
for i in range(len(nums)-1):
l=i+1
r=len(nums)-1
while l<r:
sum=nums[i]+nums[l]+nums[r]
if sum==0:
if not [nums[i],nums[l],nums[r]] in triplets:
triplets+=[[nums[i],nums[l],nums[r]]]
if sum<0:
l+=1
else:
r-=1
return triplets
谁能告诉我在哪里可以优化这段代码?
解决方案
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
N = len(nums)
for i in range(N):
if i > 0 and nums[i] == nums[i-1]:
continue
target = -nums[i]
l = i + 1
r = N - 1
while l < r:
if nums[l] + nums[r] == target:
result.append([nums[l],nums[r],nums[i]])
l = l + 1
while l <= r and nums[l] == nums[l - 1]:
l = l + 1
elif nums[l] + nums[r] > target:
r = r - 1
else:
l = l + 1
return result
推荐阅读
- r - R - 组之间的操作而不是组内的操作
- python - 标记根据表示点的数量改变大小的散点图
- regex - 空格的正则表达式仅在第一位?
- input - 从本地数据表读取的基本输入输出程序
- vue.js - 如何将对象添加到对象数组(Vue.js)
- java - 添加到 PATH 后,'javac' 不被识别为内部或外部命令、可运行程序或批处理文件
- python - 如何在 django 中自定义 403 错误页面?
- android - 创建一个卡片小部件,向上滑动时将展开到新屏幕
- shell - Curl HTTPS 返回空字符串,如何在 Linux shell / bash 脚本中设置 CURLOPT_SSL_VERIFYHOST
- mysql - MySQL 5.7:针对太多连接错误进行微调