LeetCode 1695. Maximum Erasure Value 疑问

2023-01-31 23:14:01 +08:00
 JasonLaw

我正在解决Maximum Erasure Value - LeetCode,我的 solution 如下,但是出现了 Time Limit Exceeded ,我不太明白为什么,时间复杂度明明是 O(n)呀。🤐

class Solution:
    def maximumUniqueSubarray(self, nums: List[int]) -> int:
        # sliding window solution
        res = 0
        window, l, r = set(), 0, 0
        while r < len(nums):
            while r < len(nums) and nums[r] not in window:
                window.add(nums[r])
                r += 1
            res = max(res, sum(window))
            if r == len(nums):
                return res
            while nums[r] in window:
                window.remove(nums[l])
                l += 1
        return res

不知道为什么 test case 的 nums 是空的。🤐

633 次点击
所在节点    程序员
5 条回复
chitaotao
2023-02-01 00:07:52 +08:00
sum 需要用一个变量存储,r+1 时加 nums[r],l+1 时减 nums[l]
JasonLaw
2023-02-01 07:48:39 +08:00
@chitaotao #1 我知道使用这个不会出现 Time Limit Exceeded ,是 sum(window)有问题? r + 1 时加 nums[r]应该跟 sum(window)是等价才对的。🤕
chitaotao
2023-02-01 07:55:38 +08:00
@JasonLaw sum(window) 每次调用都要从头把集合加起来
JasonLaw
2023-02-01 08:27:14 +08:00
@chitaotao #3 从头指的是从 index 0 开始?
JasonLaw
2023-02-01 09:45:11 +08:00
@chitaotao #3 我傻了😅 因为 sum(window)每次都会从 l 开始,会有很多不必要的工作,但是维护多一个 window_sum 就不会。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/912076

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX