Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How leetcode reshapes Matrix

Shulou Source: shulou.com Published: 2022-06-01 13:21:25 10月31日 Update

This article mainly shows you "leetcode how to reshape the matrix", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to reshape the matrix leetcode" this article.

I. the content of the topic

In MATLAB, there is a very useful function, reshape, that reshapes a matrix into another new matrix of different sizes, but retains its original data.

A matrix represented by a two-dimensional array and two positive integers r and c are given to represent the number of rows and columns of the desired reconstructed matrix, respectively.

The reconstructed matrix needs to populate 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 reshaping matrix is output; otherwise, the original matrix is output.

Example 1:

Enter:

Nums =

[[1,2]

[3,4]]

R = 1, c = 4

Output:

[[1,2,3,4]]

Explanation:

The result of traversing the nums in a row is [1, 2, 3, 4]. The new matrix is a 1 * 4 matrix, populating the new matrix with the previous element values one row at a time.

Example 2:

Enter:

Nums =

[[1,2]

[3,4]]

R = 2, c = 4

Output:

[[1,2]

[3,4]]

Explanation:

There is no way to convert a 2 * 2 matrix into a 2 * 4 matrix. So output the original matrix.

Note:

The width and height range of a given matrix is in [1,100].

The given r and c are positive numbers.

Second, the way to solve the problem

Get the number of rows directly according to the number of columns divided by the whole, take the remainder to get the position of each row, and assign values one by one.

Code class Solution: def matrixReshape (self, nums: list, r: int) C: int)-> list: if len (nums) * len (nums [0])! = r * c: return nums ans = [[0 for _ in range (c)] for _ in range (r)] for i in range (len (nums) * len (nums [0])): ans [I / / c] [I% c] = nums [I / / len (nums [0]) )] [I% len (nums [0])] return ansif _ name__ = ='_ main__': s = Solution () nums = [[1] 2], [3,4]] r = 1 c = 4 ans = s.matrixReshape (nums, r, c) print (ans) these are all the contents of the article "how leetcode reshapes the Matrix" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Matrix output content original article one line elements examples learning help interpretation input refactoring different feasible same two code location function Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Information vpn MariaDB Microsoft