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

LeetCode提交代码触发IndexError索引越界,本地VS运行正常求助

LeetCode合并有序数组题索引越界问题解决

题目翻译

给你两个按非递减顺序排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。

请你合并 nums2 到 nums1 中,使合并后的数组同样按非递减顺序排列。

注意:最终合并后的数组不需要返回,直接修改 nums1 即可。nums1 的初始长度为 m + n,前 m 个是有效元素,后 n 个为 0(仅用来占位);nums2 的长度为 n。

问题描述

自己写的合并数组代码在Visual Studio中运行正常,但提交到LeetCode时触发IndexError索引越界错误,失败用例为示例3。报错代码行是elif nums1[i1] <= nums2[i2]:,但我认为此时应该已经退出循环,不会执行该行。

问题代码

def merge(nums1, m, nums2, n ):
        """
        Do not return anything, modify nums1 in-place instead.
        """

        i1 = 0
        i2 = 0
        tmp = 0
        while i1 < n + m :
            if nums1[i1] == 0:
                nums1[i1] = nums2[i2]
                i1+=1
                i2+=1

            elif nums1[i1] <= nums2[i2]:
                i1 += 1
            else:
                tmp = nums2[i2]
                nums2[i2] = nums1[i1]
                nums1[i1] = tmp
                i1 += 1

错误信息

Runtime Error
IndexError: list index out of range
                      ~~~~~^^^^
    elif nums1[i1] <= nums2[i2]:
Line 16 in merge (Solution.py)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ret = Solution().merge(param_1, param_2, param_3, param_4)
Line 58 in _driver (Solution.py)
    _driver()
Line 70 in <module> (Solution.py)

问题原因

  1. 错误假设0都是占位符:代码默认nums1里的0都是待填充的位置,但实际nums1的前m个有效元素中可能本身就包含0,这会导致提前把nums2的元素塞进去,当i2达到n(nums2元素已全部处理完)后,再访问nums2[i2]就会越界。
  2. 循环条件未限制i2:循环只判断i1 < m+n,完全没考虑i2是否已经超出nums2的索引范围。比如nums2的元素全部处理完后,循环还在继续,此时i2 >= n,访问nums2[i2]必然报错。
  3. 示例3的触发场景:示例3大概率是nums1有效元素包含0,或者nums2先被处理完,刚好命中了你的代码漏洞。

修正代码

正确的思路是从后往前合并,既不会覆盖nums1的有效元素,也不用处理0的干扰:

def merge(nums1, m, nums2, n):
    # 从两个数组的末尾开始遍历
    i1 = m - 1
    i2 = n - 1
    # 指向nums1的末尾填充位置
    current = m + n - 1
    
    # 合并两个数组的有效元素
    while i1 >= 0 and i2 >= 0:
        if nums1[i1] > nums2[i2]:
            nums1[current] = nums1[i1]
            i1 -= 1
        else:
            nums1[current] = nums2[i2]
            i2 -= 1
        current -= 1
    
    # 如果nums2还有剩余元素,直接填充到nums1前面
    while i2 >= 0:
        nums1[current] = nums2[i2]
        i2 -= 1
        current -= 1

本地运行正常的原因

你在Visual Studio里测试的用例可能没覆盖到nums1有效元素含0、或者nums2先处理完的边界场景,而LeetCode的示例3刚好命中了这些情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:11:00