标签:return 判断 problem ace 简单 帮助 leetcode i++ 相等
https://leetcode.com/problems/reshape-the-matrix/description/
简单有趣,也稍微窥探了一下matlab 和numpy 里面reshape 的算法。当然现实要比这个题要复杂,比如numpy 里面reshape 可以只接受一个参数,然后自动推导出另一个参数。
具体的思路没有什么难度,主要考察细心?一是非法情况的判断,简单的就是行x列不相等的情况。然后就是怎么确保row traversing order 的问题,我通过一个简单的帮助函数来做。
class Solution { public: //return the n-th element of m using row traversing int rowTraverse(vector<vector<int>>& m, int n) { for (vector<int>& row : m) { if (n < row.size()) { return row[n]; } n -= row.size(); continue; } } vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { //check the invalid cases //since its the matrix, we can assume that every row has the same amount of elements. int rows = nums.size(); int cols = nums[0].size(); if (r*c != rows*cols) { //is that the only case? //invalid reshape, return original matrix return nums; } vector<vector<int>> m; for (int i = 0; i < r; i++) { //fill the row vector<int> _r; for (int j = 0; j < c; j++) { _r.emplace_back(rowTraverse(nums, i*c+j)); } m.emplace_back(_r); } return m; } };
标签:return 判断 problem ace 简单 帮助 leetcode i++ 相等
原文地址:https://www.cnblogs.com/agentgamer/p/9771769.html