LeetCode-566. Reshape the Matrix [Simple]-Analysis and Code (Java)

LeetCode——566. Reshape the Matrix [Reshape the Matrix][Simple]——Analysis and Code [Java]

1. Topic

In MATLAB, there is a very useful function reshape, which can reshape a matrix into another new matrix with a different size, but retain its original data.
Given a matrix represented by a two-dimensional array, and two positive integers r and c, which respectively represent the number of rows and columns of the desired reconstructed matrix.
The reconstructed matrix needs to fill all the elements of the original matrix in the same row traversal order.
If the reshape operation with the given parameters is feasible and reasonable, the new reshape matrix is ​​output; otherwise, the original matrix is ​​output.

Example 1:

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

Example 2:

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

note:

  • The width and height of a given matrix are in the range of [1, 100].
  • The given r and c are both positive numbers.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/reshape-the-matrix
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Direct conversion

(1) Thinking

The feasibility of reshaping the matrix is ​​judged by whether the number of elements is equal, and the numbers in the original matrix are sequentially filled into the new matrix if the requirements are met.

(2) Code

class Solution {
    
    
    public int[][] matrixReshape(int[][] nums, int r, int c) {
    
    
        int r0 = nums.length, c0 = nums[0].length, n = r0 * c0;
        if (r * c != n)
            return nums;
        //重塑矩阵
        int[][] outputMatrix = new int[r][c];
        for (int i = 0; i < n; i++)
            outputMatrix[i / c][i % c] = nums[i / c0][i % c0];
        return outputMatrix;
    }
}

(3) Results

Execution time: 2 ms, beating 47.97% of users
in all Java submissions ; memory consumption: 39.8 MB, beating 13.11% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/114005067