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

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

之前有刷过一些题,但都坚持不下去,现在搞个小博客,希望自己能坚持下去吧~~

 

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:

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

看意思就是重组一个矩阵:

  我的思路就是把矩阵拉成一行N列的,反正就是一行。 直接上个代码:

class Solution {public:    vector
> matrixReshape(vector
>& nums, int r, int c) { int sizeR = nums.size(), sizeC = nums[0].size(); if(sizeR*sizeC != r*c)//个数不同怎么能继续:) { return nums; } vector
> res(r, vector
(c, 0)); for(int i=0; i!=sizeR*sizeC; ++i) { res[i/r][i%c] = nums[i/sizeR][i%sizeC];//i/r某一行,i%c某一行中的某一列 } return res; }};

  看到discuss里面也有这种解法~~~

转载于:https://www.cnblogs.com/jiadyang/p/8592669.html

你可能感兴趣的文章
php修改SESSION的有效生存时间
查看>>
spring security 11种过滤器介绍
查看>>
Hibernate一对多、多对一关联
查看>>
一、记录Git使用中遇到的问题及解决方法
查看>>
学习网址
查看>>
前端表格插件datatables
查看>>
内部类
查看>>
树链剖分入门
查看>>
图解算法时间复杂度
查看>>
UI_搭建MVC
查看>>
一个样例看清楚JQuery子元素选择器children()和find()的差别
查看>>
代码实现导航栏分割线
查看>>
Windows Phone开发(7):当好总舵主 转:http://blog.csdn.net/tcjiaan/article/details/7281421...
查看>>
VS 2010打开设计器出现错误
查看>>
SQLServer 镜像功能完全实现
查看>>
Vue-详解设置路由导航的两种方法
查看>>
一个mysql主从复制的配置案例
查看>>
大数据学习系列(8)-- WordCount+Block+Split+Shuffle+Map+Reduce技术详解
查看>>
dvwa网络渗透测试环境的搭建
查看>>
Win8 安装VS2012 和 Sql Server失败问题
查看>>