109 - 566重塑矩阵

题目

在MATLAB中,有[一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。](一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。

给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重)

[给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重](一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。

给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重)构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。

如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

示例 1:

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

示例 2:

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

注意:

  • 给定矩阵的宽和高范围在 [1, 100]。

  • 给定的 r 和 c 都是正数。

解答

只能想到,全部坍缩成一维数组,然后一个个插进去。。

https://leetcode.com/problems/reshape-the-matrix/discuss/231989/simple-100-js-solution

Runtime: 76 ms, faster than 91.14% of JavaScript online submissions for Reshape the Matrix.

Memory Usage: 40.2 MB, less than 60.00% of JavaScript online submissions for Reshape the Matrix.

没想到还能有这种[].concat(...nums)这个做法。学到了。。

https://leetcode.com/problems/reshape-the-matrix/discuss/102532/A-few-JavaScript-solutions

js的一行代码版本:

Runtime: 80 ms, faster than 78.16% of JavaScript online submissions for Reshape the Matrix. Memory Usage: 38.9 MB, less than 100.00% of JavaScript online submissions for Reshape the Matrix.

go的二维数组好麻烦。。[][]int{{1, 2}, {3, 4}}要这么定义。。

https://leetcode.com/problems/reshape-the-matrix/discuss/317083/golang-solution

Runtime: 60 ms, faster than 52.05% of Go online submissions for Reshape the Matrix.

Memory Usage: 75 MB, less than 100.00% of Go online submissions for Reshape the Matrix.

https://leetcode.com/problems/reshape-the-matrix/discuss/102499/Python-Simple-with-Explanation

Runtime: 120 ms, faster than 52.08% of Python3 online submissions for Reshape the Matrix.

Memory Usage: 14.8 MB, less than 5.55% of Python3 online submissions for Reshape the Matrix.

https://leetcode-cn.com/problems/reshape-the-matrix/solution/python-die-dai-qi-by-mao1112/

Runtime: 172 ms, faster than 5.54% of Python3 online submissions for Reshape the Matrix.

Memory Usage: 14.9 MB, less than 5.55% of Python3 online submissions for Reshape the Matrix.

虽然迭代器看起来很酷,其实很耗成本😂

Last updated

Was this helpful?