在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。

    给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
    重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
    如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

    示例 1:

    输入: nums = [[1,2], [3,4]] r = 1, c = 4 输出: [[1,2,3,4]] 解释: 行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。

    示例 2:

    输入: nums = [[1,2], [3,4]] r = 2, c = 4 输出: [[1,2], [3,4]] 解释: 没有办法将 2 2 矩阵转化为 2 4 矩阵。 所以输出原矩阵。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reshape-the-matrix


    1. class Solution {
    2. public int[][] matrixReshape(int[][] nums, int r, int c) {
    3. // 无法转换直接返回
    4. if (r * c != nums.length * nums[0].length){
    5. return nums;
    6. }
    7. int[][] result = new int[r][c];
    8. int first = 0;
    9. int second = 0;
    10. for (int i = 0; i < nums.length; i++) {
    11. for (int j = 0; j < nums[0].length; j++) {
    12. // 遍历原二维数组,向新数组中添加元素
    13. result[first][second] = nums[i][j];
    14. // 如果second和c相等则说明已经添加到了最后,需要换行
    15. second++;
    16. if (second == c){
    17. second = 0;
    18. first++;
    19. }
    20. }
    21. }
    22. return result;
    23. }
    24. }