zoukankan      html  css  js  c++  java
  • 【leetcode】566. Reshape the Matrix

    原题

    In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

    You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

    The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

    If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

    Example 1:
    Input:
    nums =
    [[1,2],
    [3,4]]
    r = 1, c = 4
    Output:
    [[1,2,3,4]]
    Explanation:
    The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
    Example 2:
    Input:
    nums =
    [[1,2],
    [3,4]]
    r = 2, c = 4
    Output:
    [[1,2],
    [3,4]]
    Explanation:
    There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
    Note:
    The height and width of the given matrix is in range [1, 100].
    The given r and c are all positive.

    解析

    重组矩阵
    给一个矩阵,给一组行列数,按照给定的行列数,重组给出矩阵,使满足新的行列
    若给出矩阵不能满足新的行列,输出原矩阵

    思路

    就是循环赋值新矩阵即可

    我的解法

        public static int[][] matrixReshape(int[][] nums, int r, int c) {
            if (nums == null || nums.length <= 0 || nums[0].length <= 0 || nums.length * nums[0].length != r * c) {
                return nums;
            }
            int[][] newMatrix = new int[r][c];
            //用k,l表示新矩阵的行列下标,k<r,l<c
            int k = 0, l = 0;
            for (int i = 0; i < nums.length; i++) {
                for (int j = 0; j < nums[i].length; j++) {
                    if (l >= c) {
                        l = 0;
                        k++;
                    }
                    if (k >= r) {
                        break;
                    }
                    newMatrix[k][l++] = nums[i][j];
                }
            }
            return newMatrix;
        }
    

    最优解

    使用了除法和求余数,分别表示行列,简化了代码

    public int[][] matrixReshapeOptimized(int[][] nums, int r, int c) {
            int n = nums.length, m = nums[0].length;
            if (r * c != n * m) {
                return nums;
            }
            int[][] res = new int[r][c];
            for (int i = 0; i < r * c; i++) {
                res[i / c][i % c] = nums[i / m][i % m];
            }
            return res;
        }
    
  • 相关阅读:
    node.js 笔记一
    mysql 错误2203 1061 及安装最后出现2003现象的解决办法
    git shell 命令大全
    Mysql常用命令行大全
    php 魔术方法 说明
    php linux 环境搭建
    Linux下源码编译安装MySQL 5.5.8
    linux 压缩解压缩命令
    ftp 命令全集
    sublime text2
  • 原文地址:https://www.cnblogs.com/shanelau/p/7210926.html
Copyright © 2011-2022 走看看