LeetCode-566. Reshape the Matrix

来源:互联网 发布:php个人博客网站代码 编辑:程序博客网 时间:2024/06/05 05:28

耗时5ms,解决思路:

 1. 遍历数组先转换为一维数组或存在队列里以便重组

 2. 从队列中取数,存入r,c的二维数组中。


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;        Queue<Integer> queue=new LinkedList<>();        for(int i=0;i<nums.length;i++)        {            for(int j=0;j<nums[0].length;j++)            {               queue.add(nums[i][j]);            }        }        for(int i=0;i<r;i++)        {            for(int j=0;j<c;j++)            {               res[i][j]=queue.remove();             }        }        return res;    }}