1. 读懂题目
2. 分析,推导解法,产生思路。
解题思路:(1)逐行遍历放在对应的位置
(2)转换为一维数组;除法问题找到对应位置 。
除法问题:已知第i个元素,求在r行c列矩阵中的位置? 即为i/c行和i%c列
(3)直接调用python numpy 中的内置函数 reshape 。但运行时间和空间都很高,不推荐。
3.代码实现
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
# 逐行遍历放在对应的位置
# 给定参数的reshape不合理
if r * c != len(nums)* len(nums[0]):
return nums
# 合理,新建矩阵并放置元素
nums_new = []
row = 0
col = 0
for i in range(r):
temp_list = []
for j in range(c):
temp_list.append(nums[row][col])
if col == len(nums[0])-1: # 之前的矩阵行遍历结束
col = 0
row +=1
else:
col += 1 # 继续遍历之前矩阵的行
nums_new.append(temp_list)
return nums_new
def matrixReshape1(self, nums, r, c):
# 转换为一维数组;除法问题找到对应位置
# 除法问题:已知第i个元素,求在r行c列矩阵中的位置?
# 即为i/c行和i%c列
row = len(nums)
col = len(nums[0])
if r * c != row * col :
return nums
res = [[0]*c for _ in range(r)] # 新建一个r行c列矩阵
for x in range(r * c):
# 处理第i个元素,找到之前矩阵与新矩阵的元素并赋值
res[x//c][x%c] = nums[x//col][x%col]
return res
def matrixReshape2(self, nums, r, c):
# python numpy 中的内置函数 reshape
# 运行时间和空间都很高,不推荐
if r * c != len(nums)* len(nums[0]):
return nums
import numpy as np
# 直接调用内置函数
return np.asarray(nums).reshape(r,c)