https://leetcode.com/problems/reshape-the-matrix/#/hints
image.png
思路
- 關(guān)鍵就是原矩陣和reshape后的矩陣元素的對(duì)應(yīng)關(guān)系
- mat第k個(gè)元素為 i * 列 + j 即mat[i][j]
- i = k // 列 , j = k % 列
- k = i * reshape_col + j
- reshape[i][j] = nums[k // nums_col][k % nums_col]
Python
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
rr = len(nums)
cc = len(nums[0])
if rr * cc != r * c:
return nums
nums_new = []
for i in range(r):
tmp = []
for j in range(c):
k = i * c + j
tmp.append(nums[k // cc][k % cc])
nums_new.append(tmp)
return nums_new