<LeetCode>566. Reshape the Matrix
来源:互联网 发布:手机短信阅读软件 编辑:程序博客网 时间:2024/06/06 08:51
566. Reshape the Matrix
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input: nums = [[1,2], [3,4]]r = 1, c = 4Output: [[1,2,3,4]]Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input: nums = [[1,2], [3,4]]r = 2, c = 4Output: [[1,2], [3,4]]Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
- The height and width of the given matrix is in range [1, 100].
- The given r and c are all positive.
题目大意:
给定一个二维数组,再给定一个r,c。
求将这个二维数组转换为一个R*C的数组(原数组按行遍历)(如果合法即转换,如果不合法,就返回原数组)
思路:
如果原数组的长度和新数组(r*c)的长度是一致的,那就可以转换成功;遍历r,c,将原数组都赋值给他就可以
如果长度不一致,直接返回原数组
class Solution { public int[][] matrixReshape(int[][] nums, int r, int c) { //int[][] nums = {{1,2},{3,4}}; List<Integer> list = new ArrayList<Integer>(); //int r = 1,c = 4;// System.out.println(nums.length*nums[0].length);//长度表示,其中一定为n*m数组?? //如果不为n*m的数组??? int count = 0,len = 0; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums[i].length; j++) { count++; list.add(nums[i][j]); } } System.out.println(count); int[][] solu = new int [r][c]; if(c*r==count){ for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { solu[i][j] = list.get(len++); } } return solu; }else{ return nums; } }}
- leetcode 566. Reshape the Matrix
- LeetCode 566. Reshape the Matrix
- [LeetCode]566. Reshape the Matrix
- [leetcode]566. Reshape the Matrix
- LeetCode:566. Reshape the Matrix
- leetcode 566. Reshape the Matrix
- LeetCode | 566. Reshape the Matrix
- leetcode-566. Reshape the Matrix
- LeetCode 566.Reshape the Matrix
- LeetCode: 566. Reshape the Matrix
- LeetCode-566. Reshape the Matrix
- LeetCode * 566.Reshape the Matrix
- LeetCode: 566. Reshape the Matrix
- leetcode.566.Reshape the Matrix
- LeetCode 566. Reshape the Matrix
- [LeetCode] 566. Reshape the Matrix
- 【LeetCode】566. Reshape the Matrix
- [LeetCode]566. Reshape the Matrix
- 为什么模板不支持分离编译
- VM网络连接
- [总结]视音频编解码技术零基础学习方法
- 待处理研究问题
- pyspark-mllib
- <LeetCode>566. Reshape the Matrix
- WebDav-Milton之一
- git修改name和email
- 一个iOS 11BUG的发现、定位和解决
- 阿里IoT套件 使用记录2 消息转发
- java基础知识总结
- JS 防止网页被嵌套 防止出现登录页面被嵌套
- CComBSTR 内存泄露的问题
- Linux 测网速