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

Leetcode题目Shuffle the Array:我的Java代码为何报数组越界错误?

你的代码里有两处关键错误导致了数组越界异常,下面逐一分析并修复:

错误1:后半部分数组复制的参数错误

原代码中复制second数组时:

System.arraycopy(nums, n + 1, second, 0, n - 1);
  • 后半部分元素的起始索引应该是n(数组前n个是x₁~xₙ,第n位索引对应的就是y₁),而非n+1;
  • 复制长度应该是n,而非n-1,否则second数组只会被填充n-1个元素,后续访问会出现数据缺失或越界。
    正确的复制语句应为:
System.arraycopy(nums, n, second, 0, n);

错误2:循环逻辑错误

原循环条件i < nums.length(nums长度是2n),当i遍历到n及以上时,first[i]和second[i]会超出两个数组的边界(它们的长度都是n,最大索引为n-1),这就是触发Index 3 out of bounds for length 3的直接原因。

正确的循环应该只执行n次,每次将first[i]放到ans[2*i],second[i]放到ans[2*i+1],对应交替排列的需求。

修复后的完整代码

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] first = new int[n];
        int[] second = new int[n];
        int[] ans = new int[2 * n];
        // 复制前半部分x₁~xₙ
        System.arraycopy(nums, 0, first, 0, n);
        // 复制后半部分y₁~yₙ
        System.arraycopy(nums, n, second, 0, n);
        // 循环n次,交替填充结果数组
        for(int i = 0; i < n; i++){
            ans[2 * i] = first[i];
            ans[2 * i + 1] = second[i];
        }
        return ans;
    }
}

额外优化思路

其实可以不用额外创建first和second数组,直接从原数组取元素,节省空间:

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] ans = new int[2 * n];
        for(int i = 0; i < n; i++){
            ans[2 * i] = nums[i];
            ans[2 * i + 1] = nums[n + i];
        }
        return ans;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:55:09