You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在LeetCode中Python3的print语句会降低内存占用?

关于LeetCode「盛最多水的容器」提交中print语句对内存影响的疑问

我在解决LeetCode第11题「盛最多水的容器」时,发现了一个反常现象:添加print语句的代码运行更慢,但内存占用反而比无print的版本更低。

以下是无print语句的解决方案:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_water = 0
        p1 = 0
        p2 = len(height)-1

        while p1<p2:
            water = min(height[p1], height[p2]) * abs(p1-p2)
            if water > max_water:
                max_water = water

            if height[p1] <= height[p2]:
                p1 += 1
            elif height[p2] < height[p1]:
                p2 -= 1

        return max_water

以下是添加print语句的同逻辑解决方案:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_water = 0
        p1 = 0
        p2 = len(height)-1

        while p1<p2:
            print(p1, p2)
            water = min(height[p1], height[p2]) * abs(p1-p2)
            if water > max_water:
                max_water = water

            if height[p1] <= height[p2]:
                p1 += 1
            elif height[p2] < height[p1]:
                p2 -= 1

        return max_water

提交结果显示:含print语句的版本运行时变慢,但内存占用为26.x MB;无print语句的版本运行更快,内存占用却升至27.x MB。我原以为print语句不会影响内存,若有影响也应是增加内存,想知道这是理解错误、LeetCode平台特性还是Python运行机制导致的,恳请解惑。

内容的提问来源于stack exchange,提问作者Neel Desai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:05:10