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

Java中如何将矩阵A内1的地址存入尺寸更小的矩阵B?

面向对象编程(OOP)考试题解法

题目要求

给定一个仅由0和1组成的二维数组,需将数组中所有1的坐标存入尺寸更小的输出矩阵B:

  • 矩阵B的行数等于原数组中1的总数,列数固定为2
  • 每行依次存储对应1在原数组中的行索引和列索引
  • 存储顺序遵循原数组行优先遍历规则(从上到下、从左到右依次读取,遇到1即记录坐标)

Java实现代码

public class OnePositionCollector {
    public static int[][] getOnePositions(int[][] input) {
        // 统计原数组中1的数量,确定矩阵B的行数
        int oneCount = 0;
        for (int[] row : input) {
            for (int num : row) {
                if (num == 1) oneCount++;
            }
        }

        // 初始化输出矩阵B
        int[][] matrixB = new int[oneCount][2];
        int currentIndex = 0;

        // 遍历原数组,收集所有1的坐标
        for (int i = 0; i < input.length; i++) {
            for (int j = 0; j < input[i].length; j++) {
                if (input[i][j] == 1) {
                    matrixB[currentIndex][0] = i;
                    matrixB[currentIndex][1] = j;
                    currentIndex++;
                }
            }
        }

        return matrixB;
    }

    // 测试用例
    public static void main(String[] args) {
        int[][] testInput = {
            {1, 0, 1},
            {0, 1, 0},
            {1, 1, 0}
        };

        int[][] result = getOnePositions(testInput);
        // 打印结果
        for (int[] pos : result) {
            System.out.printf("(%d, %d)%n", pos[0], pos[1]);
        }
    }
}

代码说明

  • 先通过一次遍历统计1的数量,直接创建大小匹配的矩阵B,避免动态扩容的额外开销
  • 第二次遍历严格按行优先顺序收集坐标,确保输出符合题目要求
  • 测试用例的输出结果为:(0, 0)、(0, 2)、(1, 1)、(2, 0)、(2, 1)

内容的提问来源于stack exchange,提问作者Syed Zain Imam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:33:25