zoukankan      html  css  js  c++  java
  • Leetcode566. 重塑矩阵

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

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

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

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

     

    示例 1:

    输入:mat = [[1,2],[3,4]], r = 1, c = 4
    输出:[[1,2,3,4]]

    示例 2:

    输入:mat = [[1,2],[3,4]], r = 2, c = 4
    输出:[[1,2],[3,4]]
     

    提示:

    m == mat.length
    n == mat[i].length
    1 <= m, n <= 100
    -1000 <= mat[i][j] <= 1000
    1 <= r, c <= 300

    Python解法

    from typing import List
    class Solution:
        def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
            m,n = len(mat),len(mat[0])
            #对比重构矩阵的个数和原来矩阵的个数不一致,则返回原来的矩阵
            if (m * n != r * c):
                return mat
            else:
                templist, mat1, count = [], [], 0
                #先遍历整个list 输出子list,再从子list中遍历里面的元素,放在临时的列表中,
                #如果列表中个数达到了列数,则把这个list放在重构list中作为一行
                for childlist in mat:
                    for item in childlist:
                        templist.append(item)
                        count += 1
                        if (count == c):
                            mat1.append(templist)
                            #这边如果不清空则会把前面的临时list中的数也输出出来
                            count=0
                            templist=[]
                return mat1
            
    if __name__ == '__main__':
        a = Solution()
        b = a.matrixReshape([[1, 2], [3, 4]],4,1)
        print(b)

    java解法

       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;
            //建立队列
            Queue<Integer> que = new LinkedList<>();
            //将数组的元素放到队列中
            for(int i=0;i<nums.length;i++){
                for(int j=0;j<nums[0].length;j++){
                    que.add(nums[i][j]);
                }
            }
            
            //将队列中的元素放到指定的数组中
            for(int i=0;i<r;i++){
                for(int j=0;j<c;j++){
                    res[i][j] = que.remove();
                }
            }
            return res;
        }
    
    }
    声明 欢迎转载,但请保留文章原始出处:) 博客园:https://www.cnblogs.com/chenxiaomeng/ 如出现转载未声明 将追究法律责任~谢谢合作
  • 相关阅读:
    [LeetCode] 34. 在排序数组中查找元素的第一个和最后一个位置
    [LeetCode] 32. 最长有效括号
    [LeetCode] 31. 下一个排列
    [LeetCode] 30. 串联所有单词的子串
    [LeetCode] 29. 两数相除
    [LeetCode] 27. 移除元素
    转:畅享云时代:开发者必备的8个最佳云端集成开发环境
    转:前端集锦:十款精心挑选的在线 CSS3 代码生成工具
    转:So Easy!让开发人员更轻松的工具和资源
    转:Backbone与Angular的比较
  • 原文地址:https://www.cnblogs.com/chenxiaomeng/p/15233589.html
Copyright © 2011-2022 走看看