[英]How can I make this 3sum solution more time efficient?
I came up with a solution for the 3sum problem on leetcode but even though it passes all test codes it fails because of 'time limit exceeded'.我想出了一个解决 leetcode 上的 3sum 问题的方法,但即使它通过了所有测试代码,它也会因为“超出时间限制”而失败。
class Solution(object):
def threeSum(self, nums):
triplet_array = []
x = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
for k in range(j+1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
if i !=j and i !=k and j != k:
if [nums[i], nums[j], nums[k]] != x:
x = [nums[i], nums[j], nums[k]]
x.sort()
if x not in triplet_array:
triplet_array.append(x)
return triplet_array
I don't know how to perform the 'space/time' analysis that it keeps referencing so I'm wondering how I go about making this solution more efficient so that it will pass all test cases in the allotted time.我不知道如何执行它一直引用的“空间/时间”分析,所以我想知道我如何让这个解决方案更高效,以便在分配的时间内通过所有测试用例。
For reference the 3sum problem details can be found here: https://leetcode.com/problems/3sum/作为参考,可以在此处找到 3sum 问题的详细信息: https://leetcode.com/problems/3sum/
One tip would be to sort the incoming array first.一个提示是首先对传入的数组进行排序。 If you know that three elements at indices i, j, and k add up to more than 0, then increasing i, j, or k (so long as the list is sorted) will also be more than 0.如果您知道索引 i、j 和 k 处的三个元素加起来大于 0,那么增加 i、j 或 k(只要列表已排序)也将大于 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.