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

为何交换and连接的两个条件顺序会引发列表索引越界错误?

关于missingNumber算法中条件判断顺序引发索引越界的问题

问题描述

在实现missingNumber算法时遇到一个问题:当使用条件if nums[i] != nums[j] and nums[i] < len(nums):时,会触发列表索引越界错误;但将条件顺序调换为if nums[i] < len(nums) and nums[i] != nums[j]:时,代码可正常运行。原本以为这两行代码功能完全相同,尝试添加括号后仍报错。

完整代码

def missingNumber(self, nums: List[int]) -> int:
    i, n = 0, len(nums)
    while i < n:
        j = nums[i]
        if nums[i] != nums[j] and nums[i] < n:
            nums[i], nums[j] = nums[j], nums[i]
        else:
            i += 1
    
    for i in range(n):
        if i != nums[i]:
            return i

问题原因

这是Python中逻辑与(and)的短路求值特性导致的:

  • 当条件顺序为nums[i] != nums[j] and nums[i] < n时,Python会优先判断nums[i] != nums[j]。而j = nums[i],由于题目中数组元素是0到n中的n个数(缺失一个),必然存在元素等于n,此时j = n,但列表最大索引为n-1,访问nums[j]会直接触发索引越界。
  • 调换顺序后,先判断nums[i] < n:若该条件不成立(即nums[i] >=n),Python会直接跳过后续的nums[i] != nums[j]判断,避免了访问越界索引,自然不会报错。

本质上是利用短路求值的特性,先排除会导致索引越界的情况,再执行需要访问数组元素的判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:18:27