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

Java整数列表对称金字塔实现求助:输出异常与数组越界问题

Java金字塔构建问题及代码修复

我正在学习Java,想要解决以下问题:从给定的整数列表构建金字塔,数字需从上到下、从左到右升序排列。空白位置用0填充,为使金字塔对称,输入数字需与0交替排列。

例如,输入A={2, 4, 3, 5, 6, 1}时,金字塔应如下所示:

  • [0,0,1,0,0]
  • [0,2,0,3,0]
  • [4,0,5,0,6]

我编写了一段代码,但输出结果不符合预期,例如得到:

  • [0,1,2]
  • [0,1,2]
    而正确输出应类似:
  • [0,1,0]
  • [1,2,2]
    现在还出现了数组越界错误,请问我该如何修改代码?

原代码如下:

public int[][] buildPyramid(List<Integer> inputNumbers) 
    throws CannotBuildPyramidException {

    // Calculate the number of rows in the pyramid
    int rows = (int) (Math.sqrt(inputNumbers.size() * 2) - 1);

    // Initialize the 2D array that will hold the pyramid
    int[][] pyramid = new int[rows][rows];

    // Initialize the variables that will help us navigate through the pyramid
    int row = 0;
    int col = rows / 2;
    boolean isDown = true;

    // Iterate through the list of numbers and build the pyramid
    for (int num : inputNumbers) {
        pyramid[row][col] = num;

        if (isDown) {
            row++;
        } else {
            row--;
            col--;
        }

        if (row == rows) {
            row = rows - 2;
            col++;
            isDown = false;
        } else if (row < 0) {
            row = 1;
            isDown = true;
        }
    }

    // Print the pyramid
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < rows; j++) {
            if (pyramid[i][j] == 0) {
                System.out.print("0 ");
            } else {
                System.out.print(pyramid[i][j] + " ");
            }
        }
        System.out.println();
    }
    return pyramid;
}

问题分析与修复方案

原代码核心问题

  1. 行数计算错误:原公式无法正确匹配金字塔的数字总数规律(n行金字塔总数字数为n(n+1)/2),导致行数计算偏差
  2. 列数设置错误:对称金字塔的列数应为2*行数-1,原代码用行数作为列数,无法实现对称结构
  3. 填充逻辑错误:row/col的移动逻辑不符合"数字与0交替、对称排列"的要求,且未对输入数字排序
  4. 数组越界:列数错误+移动逻辑不合理,导致访问非法数组索引

修改后的代码

import java.util.Collections;
import java.util.List;

public int[][] buildPyramid(List<Integer> inputNumbers) 
    throws CannotBuildPyramidException {

    // 计算合法金字塔行数:满足n(n+1)/2 = 输入数字总数
    int rows = 0;
    while (rows * (rows + 1) / 2 < inputNumbers.size()) {
        rows++;
    }
    // 验证输入数量是否符合金字塔要求,不符合则抛异常
    if (rows * (rows + 1) / 2 != inputNumbers.size()) {
        throw new CannotBuildPyramidException("输入数字数量无法构成合法金字塔");
    }

    // 对称金字塔的列数为2*rows-1
    int cols = 2 * rows - 1;
    int[][] pyramid = new int[rows][cols];

    // 先对输入数字升序排序,满足题目要求
    Collections.sort(inputNumbers);

    int numIndex = 0;
    // 逐行填充数字
    for (int i = 0; i < rows; i++) {
        // 当前行的起始列:从中间位置向左偏移i个单位
        int currentCol = cols / 2 - i;
        // 每行填充i+1个数字,每隔2列放置一个(实现与0交替)
        for (int j = 0; j <= i; j++) {
            pyramid[i][currentCol] = inputNumbers.get(numIndex++);
            currentCol += 2;
        }
    }

    // 打印金字塔
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            System.out.print(pyramid[i][j] + " ");
        }
        System.out.println();
    }
    return pyramid;
}

关键修改说明

  • 合法行数验证:通过循环找到匹配输入数量的行数,同时校验输入合法性,避免无效输入
  • 对称列数设置:使用2*rows-1作为列数,保证金字塔左右对称
  • 输入排序:对输入列表升序排序,满足"从上到下、从左到右升序"的要求
  • 有序填充逻辑:每行从中间向左偏移的位置开始,每隔2列放置数字,完美实现数字与0交替的对称结构,同时避免数组越界

内容的提问来源于stack exchange,提问作者Omar Russo Castillo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:10:28