Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
最有效的3sum算法使用python解决leetcode难题_Python - Fatal编程技术网

最有效的3sum算法使用python解决leetcode难题

最有效的3sum算法使用python解决leetcode难题,python,Python,我无法通过leetcode中使用Python解决3sum问题的时间限制测试。有人能做到吗?谢谢 我的现行守则: class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ solution=[] for i in range(len(nums)):

我无法通过leetcode中使用Python解决3sum问题的时间限制测试。有人能做到吗?谢谢

我的现行守则:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        solution=[]

        for i in range(len(nums)):
            tmp={}
            for j in range(1+i,len(nums)):
                if -(nums[j]+nums[i]) in tmp:
                    solution.append(tuple(sorted((nums[j],nums[i],-(nums[j]+nums[i])))))
                else:
                    tmp[nums[j]]=j

        return list(set(solution))

不知道你的解决方案有什么问题。我认为关键在于将结果对象视为python中称为
collections.Counter的对象。我们还可以使用从输入中获取3的所有组合

import itertools
import collections

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        res = []
        for t in itertools.combinations(nums, 3):
            if sum(t) == 0:
                c = collections.Counter(t)
                if c not in res:
                    res.append(c)
        return [list(t.elements()) for t in res]

测试:

Solution().threeSum([-1, 0, 1, 2, -1, -4])
# --> [[-1, 0, 1], [-1, -1, 2]]

可能不是最有效的方法,但很简单

arr = [1,2,3,4,5,6]
val = 9

class ThreeSum:
    def solve(self, arr, val):
        res = []
        for i, v1 in enumerate(arr):
            for j, v2 in enumerate(arr):
                for k, v3 in enumerate(arr):
                    if i != j  != k != i:
                        if v1+v2+v3 == val:
                            res.append([v1, v2, v3])
        return res

print(ThreeSum().solve(arr, val))
# (1, 2, 6)
很高兴有帮助! 如果有任何疑问,请发表评论。

课堂解决方案:
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
    
        items = len(nums)
        nums.sort()
        outputs = set()
        i = 0
        while i < items-2:
            if i > 0 and nums[i] == nums[i-1]: 
                i += 1
                continue
            j = i+1
            k = items-1
            
            while j<k:
                sums = nums[j] + nums[i] + nums[k]
                if sums == 0: 
                    if (nums[i], nums[j], nums[k]) not in outputs:
                        outputs.add((nums[i], nums[j], nums[k]))
                        while j < k and nums[j] == nums[j+1]: j+=1
                        while k > j and nums[k] == nums[k-1]: k-=1
                    j += 1
                    k -= 1
                elif sums < 0: 
                    j+= 1
                    #while j < k and nums[j] == nums[j-1]: j+=1
                else:
                    k -= 1
                    #while k > j and nums[k] == nums[k+1]: k-=1

            i += 1
            
        return outputs
def threeSum(self,nums:List[int])->List[List[int]: 项目=长度(nums) nums.sort() 输出=设置() i=0 而我<第2项: 如果i>0且nums[i]==nums[i-1]: i+=1 持续 j=i+1 k=项目-1 而j和nums[k]==nums[k-1]:k-=1 j+=1 k-=1 elif总和<0: j+=1 #而jj和nums[k]==nums[k+1]:k-=1 i+=1 返回输出
描述3sum的问题是什么,我们不是通灵者。我在谷歌上搜索了3sum。我很遗憾…@FHTMitchell哦,我的天,这是NSFW lolI我有一个被接受的解决方案,但它太麻烦了,我不想展示它。但是因为leetcode非常适合,当它失败时,它会显示最新的输入,所以您可以在本地使用它,不是吗?它不应该也生成(2,3,4)吗?而且可能比询问者的代码还要慢。谢谢。3个循环可以工作,但是比使用2个循环和一个字典运行得慢。谢谢!我也尝试过收集,但在128 len的测试用例中遇到了时间限制错误:(