-
Couldn't load subscription status.
- Fork 0
Open
Description
# 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
Labels
No labels