• LeetCode 566. Reshape the Matrix


    In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

    You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

    The reshaped matrix should 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: mat = [[1,2],[3,4]], r = 1, c = 4
    Output: [[1,2,3,4]]
    

    Example 2:

    Input: mat = [[1,2],[3,4]], r = 2, c = 4
    Output: [[1,2],[3,4]]
    

    Constraints:

    • m == mat.length
    • n == mat[i].length
    • 1 <= m, n <= 100
    • -1000 <= mat[i][j] <= 1000
    • 1 <= r, c <= 300

    就是把矩阵变成r行c列的矩阵,按row遍历的顺序。就,非常直观的一道题,但是刚开始还是没在草稿纸上画一下就在瞎写导致index出错了。首先是按row col遍历的时候求它在矩阵中按row遍历的index,应该是i * col + j,毕竟一个row有col个元素。然后是最后通过index求具体哪行哪列的时候也是要针对col进行/和%。别的没啥了。

    Runtime: 1 ms, faster than 89.95% of Java online submissions for Reshape the Matrix.

    Memory Usage: 51 MB, less than 20.94% of Java online submissions for Reshape the Matrix.

    1. class Solution {
    2. public int[][] matrixReshape(int[][] mat, int r, int c) {
    3. if (mat.length * mat[0].length != r * c) {
    4. return mat;
    5. }
    6. int[][] result = new int[r][c];
    7. for (int i = 0; i < r; i++) {
    8. for (int j = 0; j < c; j++) {
    9. int index = i * c + j;
    10. result[i][j] = mat[index / mat[0].length][index % mat[0].length];
    11. }
    12. }
    13. return result;
    14. }
    15. }

  • 相关阅读:
    SpringMVC之JSR303和拦截器
    《痞子衡嵌入式半月刊》 第 97 期
    linux复习笔记02(小滴课堂)
    Simulink 自动代码生成电机控制:Keil工程转到CubeIDE相关问题(2/2)
    [leetcode 脑子急转弯] 2731. 移动机器人
    14. 线性代数 - 线性方程组
    【python】求先序排列
    【BOOST C++ 11 时钟数据】(1)计时码表(11-13)
    论文阅读[51]通过深度学习快速识别荧光组分
    南大通用GBase8s 常用SQL语句(238)
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127619922