作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/reshape-the-matrix/description/

题目描述

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

Note:

  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive.

题目大意

实现Matlab的reshape函数,就是把原来的数组逐行遍历重新改成r行,c列,如果不能实现的话就是返回原来的数组。

解题方法

变长数组

Python的list是可变的,那么一个简单的想法就是使用可变的List作为新的一行,如果新的一行的元素个数等于题目要求的列数,那么就新建一行。把每行的结果放到返回的列表中即可。

时间复杂度是O(mn),空间复杂度是O(1).没有额外空间

class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
M, N = len(nums), len(nums[0])
if M * N != r * c:
return nums
res = []
row = []
for i in range(M):
for j in range(N):
row.append(nums[i][j])
if len(row) == c:
res.append(row)
row = []
return res

求余法

这个做法是由位图法激发出来的,使用一个变量count保存现在已经有了的元素数量,那么直接可以使用res[count / c][count % c]确定轮到了的元素的位置。这个方法需要把数组提前构造好。

时间复杂度是O(mn),空间复杂度是O(1).没有额外空间

class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
M, N = len(nums), len(nums[0])
if M * N != r * c:
return nums
res = [[0] * c for _ in range(r)]
count = 0
for i in range(M):
for j in range(N):
res[count / c][count % c] = nums[i][j]
count +=1
return res

维护行列

上面的方法每次需要通过除法和求余来确定新的位置,事实上是比较耗时的。更快的方法就是维护行和列的变量,在遍历的过程中更新行和列,这样就可以对应放入的位置了。

时间复杂度是O(mn),空间复杂度是O(1).没有额外空间

class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
M, N = len(nums), len(nums[0])
if M * N != r * c:
return nums
res = [[0] * c for _ in range(r)]
row, col = 0, 0
for i in range(M):
for j in range(N):
if col == c:
row += 1
col = 0
res[row][col] = nums[i][j]
col += 1
return res

相似题目

参考资料

https://leetcode.com/articles/reshape-the-matrix/

日期

2018 年 11 月 1 日 —— 小光棍节

【LeetCode】566. Reshape the Matrix 解题报告(Python)的更多相关文章

  1. LeetCode 566 Reshape the Matrix 解题报告

    题目要求 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ...

  2. Leetcode 566. Reshape the Matrix 矩阵变形(数组,模拟,矩阵操作)

    Leetcode 566. Reshape the Matrix 矩阵变形(数组,模拟,矩阵操作) 题目描述 在MATLAB中,reshape是一个非常有用的函数,它可以将矩阵变为另一种形状且保持数据 ...

  3. LeetCode 566. Reshape the Matrix (重塑矩阵)

    In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new o ...

  4. LeetCode 566. Reshape the Matrix (C++)

    题目: In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a n ...

  5. 【LeetCode】54. Spiral Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 维护四个边界和运动方向 保存已经走过的位置 日期 题 ...

  6. 【LeetCode】867. Transpose Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 先构建数组再遍历实现翻转 日期 题目地址:https ...

  7. 【LeetCode】766. Toeplitz Matrix 解题报告

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:两两比较 方法二:切片相等 方法三:判断每条 ...

  8. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

  9. LeetCode: Search a 2D Matrix 解题报告

    Search a 2D Matrix Write an efficient algorithm that searches for a value in an m x n matrix. This m ...

随机推荐

  1. datamash 命令行下的快速计算工具

    github地址:https://github.com/agordon/datamash

  2. Oracle、MySQL关机操作步骤

    一.Oracle数据库单机关机(eg:LEAP系统) 先关闭使用数据库的应用系统,再关闭数据库 关闭数据库执行以下命令 1.关闭Oracle数据库监听器:(使用操作系统下管理Oracle的账户,关闭监 ...

  3. vim ——批量注释

    1111. ctrl+v进入列编辑模式,在编辑模式中,在行间上下移动光标,选择需要编辑哪些行的对应的列,之后使用I(大写)进入列插入.插入注释符,按两次Esc退出列编辑模式即可实现多行注释 删除注释: ...

  4. open 函数小结

    umask 掩码 open 函数的时候需要注意,掩码去反之后和设置的值想与,得到真正的值. 可以在命令行 使用umask 来查询 umask 000 设置掩码

  5. UE4之Slate: SImage

    概述 距离上次记录<UE4之Slate:纯C++工程配置>后已经好长时间了: 这个随笔来记录并分享一下SImage控件的使用,以在屏幕上显示一张图片: 目标 通过SImage控件的展示,学 ...

  6. 在idea的java开发中字符串length()方法获取长度与赋值不符的问题

    最近在开发中用到length()方法获取中文字符串的长度,发现获得的长度与实际不符.比如个String类型赋值为"中",但获取长度却是2. 这让我百思不得其解,后来突然想起来我在研 ...

  7. 在 Apple Silicon Mac 上 DFU 模式恢复 macOS 固件

    DFU 模式全新安装 macOS Big Sur 或 macOS Monterey 请访问原文链接:https://sysin.org/blog/apple-silicon-mac-dfu/,查看最新 ...

  8. c学习 - 第五章:选择结构程序设计

    5.2 关系运算符与逻辑运算符 !(非) ^ 高 算术运算符 | 关系运算符 | &&和 || | 赋值运算符 | 低

  9. Can a C++ class have an object of self type?

    A class declaration can contain static object of self type,it can also have pointer to self type,but ...

  10. Google Guava 常用集合方法

    /** * Author: momo * Date: 2018/6/7 * Description: */ public class ListTest { public static void mai ...