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

  • 相关阅读:
    [深入研究4G/5G/6G专题-46]: 5G Link Adaption链路自适应-2-常见缩略语
    Tuxera NTFS软件安装包2024最新中文版(.dmg)
    Docker基础-cgroup
    【Maven学习】3.5 实验五:让 Web 工程依赖 Java 工程
    [附源码]计算机毕业设计springboot企业售后服务管理系统
    某客户管理系统Oracle RAC节点异常重启问题详细分析记录
    Mac M1 问题记录
    java异常处理
    自定义结构体的json序列化
    表格与表单
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/127619922