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

LeetCode最长连续序列题解C++报addition of unsigned offset运行时错误

运行错误原因分析

核心错误:数组越界访问

  • 你的循环变量i从0开始遍历,第一次循环执行i=0分支时,代码里直接调用nums[i - 1]等价于访问nums[-1],属于vector的非法下标访问,操作的内存地址超出了vector分配的合法范围,直接触发了UndefinedBehaviorSanitizer的未定义行为检测报错。

你收到的报错信息就是越界访问的典型提示:

runtime error: addition of unsigned offset to 0x603000000070 overflowed to 0x60300000006c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior

额外逻辑漏洞

  • 没有处理输入数组为空的边界情况:如果nums是空数组,代码初始化curr和longest为1,最终会返回1,而空数组的最长连续序列结果应为0,不符合题目要求。
  • 没有处理数组长度为1的边界情况,原逻辑从i=0遍历也会触发越界。
修正后的代码示例
int longestConsecutive(vector<int>& nums) {
    // 先处理空数组边界
    if (nums.empty()) return 0;
    sort(nums.begin(), nums.end());
    
    int curr = 1;
    int longest = 1;
    // 遍历从i=1开始,避免访问i-1为负数
    for(int i = 1; i < nums.size(); i++){
        if(nums[i] != nums[i - 1]) {
            if(nums[i] == nums[i - 1] + 1) {
                curr += 1;
            } else {
                longest = max(longest, curr);
                curr = 1;    
            }
        }
    }
    return max(curr, longest);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:45:07