LeetCode之Reshape the Matrix

xiaoxiao2021-02-27  651

题目概述:

把一个二维数组的矩阵重塑成一个与之不同大小的新矩阵。

思路:

注意只有两个矩阵的元素个数相同时,这个转换才能完成。

示例:

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.

代码:

class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { //如果旧矩阵和新矩阵的元素个数不同,就返回旧矩阵 if((nums.size()*nums[0].size())!=(r*c)) { return nums; } int length=nums[0].size();//nums的列数 int k=0,l=0; //定义一个r*c的二维数组 vector<vector<int>> array(r); for(int i=0;i<r;i++) { array[i].resize(c); } //给新矩阵赋值 for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { array[i][j]=nums[k][l]; l++; if(l==length) { l=0; k++; } } } return array; } };

转载请注明原文地址: https://www.6miu.com/read-472.html

最新回复(0)