题目描述

自己解法
先把原矩阵转换为一个列表,再依次读入:
时间复杂度
O
(
m
∗
n
)
O(m*n)
O(m∗n),空间复杂度
O
(
m
∗
n
)
O(m*n)
O(m∗n)
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
if r * c != len(nums) * len(nums[0]):
return nums
ans = []
L = []
for i in range(len(nums)):
for j in range(len(nums[0])):
L.append(nums[i][j])
p = 0
for i in range(r):
temp = []
for j in range(c):
temp.append(L[p])
p += 1
ans.append(temp)
return ans

题解区解法
官方解答
详细参考:官方解答。
不使用额外空间:
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int[][] res = new int[r][c];
if (nums.length == 0 || r * c != nums.length * nums[0].length)
return nums;
int rows = 0, cols = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
res[rows][cols] = nums[i][j];
cols++;
if (cols == c) {
rows++;
cols = 0;
}
}
}
return res;
}
}
除法和取模:
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int[][] res = new int[r][c];
if (nums.length == 0 || r * c != nums.length * nums[0].length)
return nums;
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
res[count / c][count % c] = nums[i][j];
count++;
}
}
return res;
}
}
用户解答
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
m,n=len(nums),len(nums[0])
if m*n!=r*c:
return nums
res=[i for j in nums for i in j]
return [res[i:i+c] for i in range(0,len(res),c)]
class Solution:
def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
def Y(M):
for R in M:
yield from R
if r * c != len(nums) * len(nums[0]):
return nums
it = Y(nums)
return [[next(it) for _ in range(c)] for _ in range(r)]
本文深入解析了矩阵重塑算法,提供了多种实现方式,包括Python和Java的解决方案,探讨了时间复杂度和空间复杂度,并展示了如何在不使用额外空间的情况下进行矩阵重塑。
- LeetCode&spm=1001.2101.3001.5002&articleId=107326992&d=1&t=3&u=249b6e33dfa6488280ea55464eb231e8)
1110

被折叠的 条评论
为什么被折叠?



