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

CodeSignal adjacentElementsProduct问题运行时错误排查求助

你的代码运行时错误原因分析

核心运行时错误原因:数组越界

你把存储相邻乘积的数组b固定设为长度5,但inputArray的长度可能远大于6(循环i < inputArray.length-1会遍历到inputArray.length-2的位置)。比如当inputArray长度为7时,i会取到5,而b的索引范围仅为0-4,此时访问b[5]会直接触发ArrayIndexOutOfBoundsException,这就是CodeSignal上报运行时错误的关键原因。你在Eclipse能正常运行,大概率是测试时用的inputArray长度刚好≤6,没触发越界场景,但CodeSignal的测试用例包含了更长的数组。

其他问题

  • 语法笔误:你粘贴的代码里int[] b = new int [5];e多了个多余的e,这是语法错误,正常编译都无法通过,推测是你粘贴时的输入错误,实际运行的代码里没有这个问题。
  • 逻辑缺陷(非运行时错误,但影响结果):你把max初始化为0,如果所有相邻元素的乘积都是负数,最终返回的0会是错误结果。正确的做法应该是把max初始化为第一个相邻元素的乘积(max = inputArray[0] * inputArray[1]),再后续遍历更新最大值。

修正后的参考代码(解决数组越界问题)

int solution(int[] inputArray) {
    int[] b = new int[inputArray.length - 1];
    int max = inputArray[0] * inputArray[1];
    
    for(int i = 0; i < inputArray.length - 1; i++) {
        b[i] = inputArray[i] * inputArray[i+1];
        if(b[i] > max) {
            max = b[i];
        }
    }
    return max;
}

当然,更简洁的写法可以省去额外数组,直接在遍历过程中计算并比较:

int solution(int[] inputArray) {
    int max = inputArray[0] * inputArray[1];
    for(int i = 1; i < inputArray.length - 1; i++) {
        int product = inputArray[i] * inputArray[i+1];
        if(product > max) {
            max = product;
        }
    }
    return max;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:45:40