• 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. }

  • 相关阅读:
    12.SpringBoot之RestTemplate的使用
    1、云原生安全之K8S的部署与常用命令
    CMSIS-RTOS在stm32使用
    React Hook总结
    数组类型和多维数组本质
    Vue学习(十九)插槽
    统信系统UOS桌面版V20 用户手册
    软件测试中如何测试日志内容
    Win11怎么调亮度?Win11调屏幕亮度的四种方法
    TS类型全解
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127619922