Reshape the Matrix

原题: https://leetcode.com/problems/reshape-the-matrix/description/

题意: 给定二维矩阵nums,将其转化为r行c列的新矩阵。若无法完成转化,返回原矩阵。

约定:(1)给定矩阵的高度和宽度范围[1, 100];(2)r和c都是正数。

例子: 

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.

标签: matrix、nums、reshape、矩阵、row、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • SLPH
    2017-08-12 17:57:53 1楼#1层
    Java:
    public class Solution {  
        public int[][] matrixReshape(int[][] nums, int r, int c) {  
            int original_r = nums.length;  
            int original_c = nums[0].length;  
            if (original_r * original_c == r * c) {  
                int[][] result = new int[r][c];  
                for (int i = 0; i < r * c; i++) {  
                    result[i / c][i % c] = nums[i / original_c][i % original_c];  
                }  
                return result;  
            } else {  
                return nums;  
            }  
        }  
    }
  • SLPH
    2017-08-12 17:58:41 2楼#1层
    C++解法一:
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int m = nums.size(), n = nums[0].size();
            if (m * n != r * c) return nums;
            vector<vector<int>> res(r, vector<int>(c));
            for (int i = 0; i < r; ++i) {
                for (int j = 0; j < c; ++j) {
                    int k = i * c + j;
                    res[i][j] = nums[k / n][k % n];
                }
            }
            return res;
        }
    };
  • SLPH
    2017-08-12 17:58:57 3楼#1层
    C++解法二:
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int m = nums.size(), n = nums[0].size();
            if (m * n != r * c) return nums;
            vector<vector<int>> res(r, vector<int>(c));
            for (int i = 0; i < r * c; ++i) {
                res[i / c][i % c] = nums[i / n][i % n];
            }
            return res;
        }
    };
  • 回复
隐藏