Skip to content

566. Reshape the Matrix #9

@w4irdo

Description

@w4irdo
# Python 1
import numpy as np
class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        try:
            return np.reshape(nums, [r, c]).tolist()
        except:
            return nums

# Python 2
class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        if nums is None:
            return None
        i = len(nums)
        j = len(nums[0])
        if r * c != i * j:
            return nums
        
        tem = []
        re = []
        for row in range(i):
            for col in range(j):
                tem.append(nums[row][col])
        
        for ind in range(0, r*c, c):
            re.append(tem[ind:ind+c])
        
        return re
                
        
# Java
class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c){
            return nums;
        }
        
        int index = 0;
        int [][] reshapedNums = new int[r][c];
        
        for(int i = 0; i < r; i++){
            for(int j = 0;j < c; j++){
                reshapedNums[i][j] = nums[index / n][index % n];
                index++;
            }
        }
        
        return reshapedNums;
    }
}
  • Python 版,用到矩阵,Numpy 直接解决不在话下;Python 2 版本要快很多。
  • Java 版:reshapedNums[i][j] = nums[index / n][index % n]理解透蛮关键的。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions