简体   繁体   English

3 Python 中的求和问题 3、Leetcode 超过时间限制

[英]3Sum Problem in Python 3, Time Limit Exceeded in Leetcode

I tried solving the 3Sum problem on Leetcode in python 3 but it shows that the time limit has exceeded for my solution.我尝试在 python 3 中解决 Leetcode 上的 3Sum 问题,但它表明我的解决方案已超过时间限制。 3Sum problem is as follows: Given array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? 3Sum问题如下:给定n个整数的数组nums,nums中是否存在元素a、b、c使得a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.在数组中找到所有唯一的三元组,其总和为零。

Note:笔记:

The solution set must not contain duplicate triplets.解决方案集不得包含重复的三元组。

Example:例子:

Given array nums = [-1, 0, 1, 2, -1, -4],给定数组 nums = [-1, 0, 1, 2, -1, -4],

A solution set is:一个解决方案集是:

[-1, 0, 1], [-1, -1, 2]. [-1, 0, 1], [-1, -1, 2]。 I have been trying to figure it for a long time but in vain.我一直想弄清楚它很长一段时间,但徒劳无功。 Also, I am new to this so please bear with me.另外,我是新手,所以请多多包涵。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]
        res =[]
        size = len(nums)
        nums.sort()
        for i in range(size-2):
         
            if i> 0 and nums[i] == nums[i-1]:
                continue

            low = i+1
            high = size - 1

            while(low<high):
                val = nums[low]+nums[high] + nums[i]
                if(val < 0)  or ((low < high) and nums[low] == nums[low+1]):

                    low = low + 1
                elif( val > 0) or ((low < high) and nums[high] == nums[high-1]):

                    high = high - 1
                else:
                    res.append( (nums[i], nums[low], nums[high]))
        return(res)

Can someone please tell me what's the mistake.有人可以告诉我是什么错误。

You have to do that O(N ^ 2).你必须这样做 O(N ^ 2)。 O(N ^ 3) is not acceptable: O(N ^ 3) 是不可接受的:

from typing import List

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        unique_triplets = []
        nums.sort()
        for i in range(len(nums) - 2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            lo = i + 1
            hi = len(nums) - 1
            while lo < hi:
                target_sum = nums[i] + nums[lo] + nums[hi]
                if target_sum < 0:
                    lo += 1
                if target_sum > 0:
                    hi -= 1
                if target_sum == 0:
                    unique_triplets.append((nums[i], nums[lo], nums[hi]))
                    while lo < hi and nums[lo] == nums[lo + 1]:
                        lo += 1
                    while lo < hi and nums[hi] == nums[hi - 1]:
                        hi -= 1
                    lo += 1
                    hi -= 1
        return unique_triplets

One of LeetCode's solution: LeetCode 的解决方案之一:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = []
        found, dups = set(), set()
        seen = {}
        for i, val1 in enumerate(nums):
            if val1 not in dups:
                dups.add(val1)
                for j, val2 in enumerate(nums[i+1:]):
                    complement = -val1 - val2
                    if complement in seen and seen[complement] == i:
                        min_val = min((val1, val2, complement))
                        max_val = max((val1, val2, complement))
                        if (min_val, max_val) not in found:
                            found.add((min_val, max_val))
                            res.append([val1, val2, complement])
                    seen[val2] = i
        return res

References参考

  • For additional details, you can see the Discussion Board .有关其他详细信息,您可以查看讨论板 There are plenty of accepted solutions, explanations, efficient algorithms with a variety of languages, and time/space complexity analysis in there.那里有很多公认的解决方案、解释、各种语言的高效算法以及时间/空间复杂度分析。

Your while loop runs forever if it ever finds a result to put into the results list.如果找到要放入结果列表的结果,您的while循环将永远运行。 That's because the else clause inside your while loop doesn't do anything to change the loop condition, so it will just keep running with the same low , high and i values until you run out of memory to store them.那是因为while循环中的else子句不会改变循环条件,所以它只会以相同的lowhighi值继续运行,直到你用完 memory 来存储它们。

I suspect you want to advance both low and high after appending a solution to the results:我怀疑您想在将解决方案附加到结果后同时提高lowhigh

        while(low<high):
            val = nums[low]+nums[high] + nums[i]
            if(val < 0)  or ((low < high) and nums[low] == nums[low+1]):

                low = low + 1
            elif( val > 0) or ((low < high) and nums[high] == nums[high-1]):

                high = high - 1
            else:
                res.append( (nums[i], nums[low], nums[high]))
                low = low + 1
                high = high - 1

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

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