566. 重塑矩阵(简单)- LeetCode

本文深入解析了矩阵重塑算法,提供了多种实现方式,包括Python和Java的解决方案,探讨了时间复杂度和空间复杂度,并展示了如何在不使用额外空间的情况下进行矩阵重塑。

题目描述

在这里插入图片描述

自己解法

先把原矩阵转换为一个列表,再依次读入:
时间复杂度 O ( m ∗ n ) O(m*n) O(mn),空间复杂度 O ( m ∗ n ) O(m*n) O(mn)

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;
    }
}
用户解答

使用Python切片

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)]

Pyhton迭代器

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)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值