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

LeetCode与VSCode中Python实现寻找两个正序数组的中位数结果不一致

LeetCode「寻找两个正序数组的中位数」代码问题排查

问题背景

最近开始学习Python,卡在LeetCode的4. 寻找两个正序数组的中位数题目上。题目要求:给定两个大小为m和n的正序数组nums1、nums2,返回它们的中位数,且时间复杂度需达到O(log(m+n))。

我的思路是只构建合并后数组的前半部分,用coffin列表存储元素,pos变量计数,当pos达到总长度的一半时停止计算并返回中位数。但同样逻辑的代码在VSCode中运行正常,提交到LeetCode判题系统却输出错误结果:

  • 输入[1,2],[3,4]时,VSCode调用函数返回2.5,LeetCode的Solution类方法却返回2.0。
  • 我怀疑LeetCode保留了之前测试用例(输入[1,2],[3])的con值,但con是函数内部定义的变量,每次调用应该会重新初始化。

代码对比

VSCode测试代码

def fn(nums1,nums2):
    pos = -1
    coffin = []
    con = len(nums1) + len(nums2)
    for i in nums1:
        for x in nums2:
            if x > i:
                coffin.append(i)
                pos += 1
                break
            #if x == i: # Median doesn't account for repeated number? for leetcode
                coffin.append(i)
                coffin.append(x)
                nums2 = nums2[1:]
                pos += 2
                break
            else:
                coffin.append(x)
                nums2 = nums2[1:]
                pos += 1
            if pos >= con / 2:
                if con % 2 == 0:
                    return (coffin[int(con / 2 -1)] + coffin[int(con / 2)]) / 2
                else:
                    return coffin[int(con/2)]
    for e in nums2:
        coffin.append(e)
        pos += 1
        if pos >= con / 2:
                if con % 2 == 0:
                    return (coffin[int(con / 2 -1)] + coffin[int(con / 2)]) / 2
                else:
                    return coffin[int(con/2)]

LeetCode提交代码

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
    pos = -1
    coffin = []
    con = len(nums1) + len(nums2)
    for i in nums1:
        for x in nums2:
            if x > i:
                coffin.append(i)
                pos += 1
                break
            #if x == i: # Median doesn't account for repeated number? for leetcode
                coffin.append(i)
                coffin.append(x)
                nums2 = nums2[1:]
                pos += 2
                break
            else:
                coffin.append(x)
                nums2 = nums2[1:]
                pos += 1
            if pos >= con / 2:
                if con % 2 == 0:
                    return (coffin[int(con / 2 -1)] + coffin[int(con / 2)]) / 2
                else:
                    return coffin[int(con/2)]

    for e in nums2:
        coffin.append(e)
        pos += 1
        if pos >= con / 2:
                if con % 2 == 0:
                    return (coffin[int(con / 2 -1)] + coffin[int(con / 2)]) / 2
                else:
                    return coffin[int(con/2)]

核心疑惑

为什么相同逻辑的代码在本地与LeetCode判题系统中结果不一致?代码是否存在隐藏的状态保留问题?或是LeetCode执行环境有特殊机制导致该问题?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:10:22