LeetCode566——Reshape the Matrix
来源:互联网 发布:陆树铭 关羽 知乎 编辑:程序博客网 时间:2024/05/16 07:07
题意
将一个矩阵转换成指定行列数的新矩阵,若原矩阵元素数目与新矩阵数目不等,则返回新矩阵。
代码
方法一:将原矩阵中的元素依次取出同时放入新矩阵。
public class Solution { public int[][] matrixReshape(int[][] nums, int r, int c) { int r_original=nums.length; int c_original=nums[0].length; if(r_original*c_original==r*c){ int[][] newArray=new int[r][c]; for(int i=0;i<r_original*c_original;i++){ newArray[i/c][i%c]=nums[i/c_original][i%c_original]; } return newArray; } else return nums; }}
此处有两点需要注意:1、通过nums.length确定原矩阵的函数,通过nums[0].length确定原矩阵的列数;
2、通过nums[i/c_original][i%c_original]将原矩阵中的元素依次按行取出。
方法二:先将原矩阵中的元素按行取出放入队列,然后再从队列中存入新矩阵
import java.util.LinkedList;import java.util.Queue;public class Solution2 { public int[][] matrixReshape(int[][] nums, int r, int c){ int r_original=nums.length; int c_original=nums[0].length; if(r_original*c_original==r*c) { 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]); } } int[][] result=new int[r][c]; for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { result[i][j]=queue.remove(); } } return result; } else return nums; }}
此方法应该注意的是队列的使用以及
add 在队列尾部增加一个元素
remove 移除并返回队列头部的元素
阅读全文
0 0
- LeetCode566——Reshape the Matrix
- LeetCode566. Reshape the Matrix
- LeetCode566. Reshape the Matrix
- leetcode566. Reshape the Matrix
- leetcode566. Reshape the Matrix
- Leetcode566. Reshape the Matrix
- Reshape the Matrix---LeetCode566
- python--leetcode566. Reshape the Matrix
- 19.leetCode566:Reshape the Matrix
- LeetCode566:reshape matrix 解答
- LeetCode ——566. Reshape the Matrix
- Leetcode学习(5)—— Reshape the Matrix
- Reshape the Matrix
- 566. Reshape the Matrix
- 566.Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- Java 数据流
- 【分布式架构】jedisLock—redis分布式锁实现
- 顺序表应用4-2:元素位置互换之逆置算法(数据改进)
- 7. Reverse Integer
- Linux之Sed工具的使用详解
- LeetCode566——Reshape the Matrix
- struts2文件上传详解.
- python--- 难缠符号,二进制,位移,取反,异或,按位与,按位或,奇偶判断,硬盘容量,真假
- hdu_2795_线段树入门_线段树由树状数组转坑原本数组模拟
- E
- mybatis默认别名
- 欢迎使用CSDN-markdown编辑器
- 待处理
- 装饰模式