• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

youyou-dev

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

将一维数组转换成二维数组

将一维数组转换成二维数组

目录
  • 将一维数组转换成二维数组
    • 解法一:常规解法
    • 解法二
        • 索引映射原理
    • 解法三:力扣官方题解
      • 循环步长: i += n
      • System.arraycopy :高效复制

image

解法一:常规解法

使用双循环

class Solution {
    public int[][] construct2DArray(int[] original, int m, int n) {
        int len = original.length;
        int index = 0;
        int[][] result = new int[m][n];
        if(len != m * n)  return new int[0][0];
        for (int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++){
               result[i][j]=original[index++] 
            }
        }
        return result;
    }
}

时间复杂度为 O(m*n),空间复杂度 O(1)

解法二

class Solution {
    public int[][] construct2DArray(int[] original, int m, int n) {
        if (original.length != m * n) {
            return new int[0][0];  
        }
        int[][] result = new int[m][n];
        for (int i = 0; i < original.length; i++) {
            result[i / n][i % n] = original[i];
        }
        return result;
    }
}

时间复杂度为 O(m*n),空间复杂度 O(1)

索引映射原理

  • 行号:row = i / n(整数除法)
    因为每行有 n 个元素,前 n 个元素(i = 0 ~ n-1)属于第 0 行;接下来 n 个元素(i = n ~ 2n-1)属于第 1 行,以此类推。
  • 列号:col = i % n(取余运算)
    每一行内,列号从 0 到 n-1 循环。

解法三:力扣官方题解

class Solution {
    public int[][] construct2DArray(int[] original, int m, int n) {
        // 1. 长度校验:总元素个数必须等于 m * n
        if (original.length != m * n) {
            return new int[0][];   // 返回一个空的二维数组(0行,列数未指定)
        }

        // 2. 创建目标二维数组,所有元素初始为 0
        int[][] ans = new int[m][n];

        // 3. 循环复制每一行
        for (int i = 0; i < original.length; i += n) {
            // 将 original 中从索引 i 开始的 n 个元素,复制到 ans 的第 (i/n) 行,从第 0 列开始
            System.arraycopy(original, i, ans[i / n], 0, n);
        }

        // 4. 返回构造好的二维数组
        return ans;
    }
}

循环步长: i += n

  • 因为每行有 n 个元素,所以每次跳过一整行的数据,i 的取值依次为:0, n, 2n, ..., (m-1)*n。
  • 循环次数正好为 m 行。

System.arraycopy :高效复制

System.arraycopy(original, i, ans[i / n], 0, n);
  • 参数含义:
    • original:源数组。
    • i:源数组起始位置(当前行的第一个元素在原数组中的索引)。
    • ans[i / n]:目标数组的那一行(ans 的第 i/n 行,因为 i/n 正好是行号)。
    • 0:目标行的起始列(列 0)。
    • n:要复制的元素个数(即每行的列数)。

链接:https://leetcode.cn/problems/convert-1d-array-into-2d-array/solutions/1185411/jiang-yi-wei-shu-zu-zhuan-bian-cheng-er-zt47o/
来源:力扣(LeetCode)

posted on 2026-03-29 18:15  U~U  阅读(2)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3