博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】566. Reshape the Matrix
阅读量:5233 次
发布时间:2019-06-14

本文共 2166 字,大约阅读时间需要 7 分钟。

原题

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 = 4
Output:
[[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 = 4
Output:
[[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.

解析

重组矩阵

给一个矩阵,给一组行列数,按照给定的行列数,重组给出矩阵,使满足新的行列
若给出矩阵不能满足新的行列,输出原矩阵

思路

就是循环赋值新矩阵即可

我的解法

public static int[][] matrixReshape(int[][] nums, int r, int c) {        if (nums == null || nums.length <= 0 || nums[0].length <= 0 || nums.length * nums[0].length != r * c) {            return nums;        }        int[][] newMatrix = new int[r][c];        //用k,l表示新矩阵的行列下标,k
= c) { l = 0; k++; } if (k >= r) { break; } newMatrix[k][l++] = nums[i][j]; } } return newMatrix; }

最优解

使用了除法和求余数,分别表示行列,简化了代码

public int[][] matrixReshapeOptimized(int[][] nums, int r, int c) {        int n = nums.length, m = nums[0].length;        if (r * c != n * m) {            return nums;        }        int[][] res = new int[r][c];        for (int i = 0; i < r * c; i++) {            res[i / c][i % c] = nums[i / m][i % m];        }        return res;    }

转载于:https://www.cnblogs.com/shanelau/p/7210926.html

你可能感兴趣的文章
721. Accounts Merge
查看>>
OpenCv-Python 图像处理基本操作
查看>>
「Unity」委托 将方法作为参数传递
查看>>
重置GNOME-TERMINAL
查看>>
redis哨兵集群、docker入门
查看>>
hihoCoder 1233 : Boxes(盒子)
查看>>
oracle中anyData数据类型的使用实例
查看>>
C++对vector里面的元素排序及取任意重叠区间
查看>>
软件测试——性能测试总结
查看>>
12.4站立会议
查看>>
Java Concurrentmodificationexception异常原因和解决方法
查看>>
客户端访问浏览器的流程
查看>>
codeforces水题100道 第二十二题 Codeforces Beta Round #89 (Div. 2) A. String Task (strings)
查看>>
c++||template
查看>>
[BZOJ 5323][Jxoi2018]游戏
查看>>
编程面试的10大算法概念汇总
查看>>
Vue
查看>>
python-三级菜单和购物车程序
查看>>
条件断点 符号断点
查看>>
VMware12 + Ubuntu16.04 虚拟磁盘扩容
查看>>