原题

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<r,l<c
int k = 0, l = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
if (l >= 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;
}

最新文章

  1. mariadb 10.2.3支持oracle execute immediate语法
  2. hdu 4039 2011成都赛区网络赛I ***
  3. Jmeter 分布式性能测试
  4. 【教程】手把手教你如何利用工具(IE9的F12)去分析模拟登陆网站(百度首页)的内部逻辑过程
  5. poi读写word模板 / java生成word文档
  6. EditPlus使用心得及常用快捷键
  7. TCP/IP协议原理学习笔记
  8. 简单改造 starling 中的 AssetManager 让其更适合 批次加载纹理
  9. C\C++代码优化的27个建议
  10. [一个经典的多线程同步问题]解决方案一:关键段CS
  11. nginx在linux下的目录结构
  12. linux 配置tomcat服务器
  13. js设置文本框只能输入数字
  14. nopCommerce 3.9 大波浪系列 之 可退款的支付宝插件(上)
  15. 纯代码实现wordpress文章隐藏内容评论可见
  16. 批量数据复制SqlBulkCopy使用经验点滴(特别是超时处理)
  17. JetBrain系列IDE提示Filesystem Case-Sensitivity Mismatch的解决
  18. Spring之bean的生命周期
  19. linux 基础 文件系统 用户权限
  20. luogu P1357 花园

热门文章

  1. 文件被sourceTree忽略了怎么办
  2. Docker镜像仓库Harbor搭建
  3. 线程.Qt更新界面
  4. ELK实战搭建+x-pack安全认证
  5. fastadmin 后台view data-source关联报500错误问题
  6. Python 实现把两个排好序的的列表合并成一个排序列表
  7. javaIO -- File源码
  8. Laravel安装和composer安装
  9. Django之Form与ModelForm组件
  10. MongoDB 关系运算符及统计个数及跳过分页