简体   繁体   English

如何加速python中的嵌套for循环?

[英]How to speed up nested for loop in python?

My leetcode algorithm for 3sum problem can't make through the 311th test case - the time limit exceeded (the list length is 3000)我的3sum问题的leetcode算法无法通过第311个测试用例-超出时间限制(列表长度为3000)

The nested loop seems to be the most inefficient part of my algorithm.嵌套循环似乎是我算法中效率最低的部分。 Is there a way to make it more efficient by using different approach?有没有办法通过使用不同的方法来提高效率?

def threeSum(self, nums: List[int]) -> List[List[int]]:
    result = []

    for i, e in enumerate(nums):
        for i2, e2 in enumerate(nums[i+1:]):
            e3 = -1 * (e + e2)
            l = [e,e2,e3]
            l.sort()
            if l in result:
                continue

            nums[i] = ''
            nums[i2+i+1] = ''
            if e3 in nums:
                result.append(l)
            nums[i] = e
            nums[i2+i+1] = e2

    return result

I also tried removing l.sort(), but time limit is still exceeded:我也尝试删除 l.sort(),但仍然超出了时间限制:

nums.sort()
    for i, e in enumerate(nums):
        for i2, e2 in enumerate(nums[i+1:]):
            e3 = -1 * (e + e2)
            l = []
            if e3 > e2:
                l = [e,e2,e3]
            elif e3 < e:
                l = [e3,e,e2]
            else:
                l = [e,e3,e2]
            if l in result:
                continue

            nums[i] = ''
            nums[i2+i+1] = ''
            if e3 in nums:
                result.append(l)
            nums[i] = e
            nums[i2+i+1] = e2

    return result

First of all, one ground rule is to never change the list you are iterating over.首先,一个基本规则是永远不要更改您正在迭代的列表。

Second thing, you need to change the way you think about it.其次,你需要改变你的想法。 Think how you can reduce the existing problem into a multiple 2sum problems, and solve each and every one of the individually.想想如何将现有问题简化为多个 2su​​m 问题,并单独解决每个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM