博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA代码—算法基础:矩阵变换问题
阅读量:4042 次
发布时间:2019-05-24

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

矩阵变换问题

问题描述

原问题链接:

给定一个二维数组代表一个矩阵。例如:

[ [1,2],
[3,4] ]

这个矩阵具有2行2列。

给定整数r和c分别代表需要将原矩阵变换为目标矩阵的行数和列数。

例如:r=1,c=4,表示将原2行2列的矩阵变换为1行4列的矩阵。
要求:在从原矩阵向目标矩阵变换时,需要保持原矩阵中行元素的顺序。
(原文描述:The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.)

Note:

The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.

问题分析

矩阵变换时可以先考虑一个基本问题,例如:原矩阵有2行2列,需要变换的目标矩阵是 1行5列,则不能变换。

换句话说:原矩阵和目标矩阵应该需要相同的元素个数。
这样的话具有一个基本的判断条件存在: 原矩阵行数 * 列数 = 变换后的矩阵的行数 * 列数
否则,就无法变换。

如果可以变换,则再进一步考虑变换规律。

算法设计

public int[][] matrixReshape(int[][] nums, int r, int c) {        int row = nums.length, col = nums[0].length;        int newNum = r*c;        int oldNum = row * col;        if(newNum!=oldNum) return nums;        int[][] ret = new int[r][c];        int ri = 0, ci = 0;        for(int i=0;i

测试代码如下:

package com.bean.algorithmbasic;public class MatrixReshapeDemo {    public int[][] matrixReshape(int[][] nums, int r, int c) {        int row = nums.length, col = nums[0].length;        int newNum = r*c;        int oldNum = row * col;        if(newNum!=oldNum) return nums;        int[][] ret = new int[r][c];        int ri = 0, ci = 0;        for(int i=0;i

(完)

转载地址:http://kwtdi.baihongyu.com/

你可能感兴趣的文章
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
Ubuntu 13.10使用fcitx输入法
查看>>
pidgin-lwqq 安装
查看>>
mint/ubuntu安装搜狗输入法
查看>>
C++动态申请数组和参数传递问题
查看>>
opencv学习——在MFC中读取和显示图像
查看>>
retext出现Could not parse file contents, check if you have the necessary module installed解决方案
查看>>
pyQt不同窗体间的值传递(一)——对话框关闭时返回值给主窗口
查看>>
linux mint下使用外部SMTP(如网易yeah.net)发邮件
查看>>