算法21----重塑矩陣 LeetCode566
阿新 • • 發佈:2018-08-11
style from class leetcode 轉化 mce type obj ext
1、題目
在MATLAB中,有一個非常有用的函數 reshape
,它可以將一個矩陣重塑為另一個大小不同的新矩陣,但保留其原始數據。
給出一個由二維數組表示的矩陣,以及兩個正整數r
和c
,分別表示想要的重構的矩陣的行數和列數。
重構後的矩陣需要將原始矩陣的所有元素以相同的行遍歷順序填充。
如果具有給定參數的reshape
操作是可行且合理的,則輸出新的重塑矩陣;否則,輸出原始矩陣。
示例 1:
輸入: nums = [[1,2], [3,4]] r = 1, c = 4 輸出: [[1,2,3,4]] 解釋: 行遍歷nums的結果是 [1,2,3,4]。新的矩陣是 1 * 4 矩陣, 用之前的元素值一行一行填充新矩陣。
示例 2:
輸入: nums = [[1,2], [3,4]] r = 2, c = 4 輸出: [[1,2], [3,4]] 解釋: 沒有辦法將 2 * 2 矩陣轉化為 2 * 4 矩陣。 所以輸出原矩陣。
註意:
- 給定矩陣的寬和高範圍在 [1, 100]。
- 給定的 r 和 c 都是正數。
2、思路
先將原始矩陣轉化成一個叠代器,所有數都放進去,【也可以放進隊列中】,然後創建一個新的矩陣(大小為reshape的大小),一個一個往裏放數。
將列表轉化成叠代器可以用itertools模塊下chain.from_iterable(列表) 函數。然後用next函數一個一個取數
還有一個重點:創建二維矩陣的一種方法:
for i in range(r):
result.append([])
for j in range(c):
result[i].append(next(chainnum))
第二種:result = [ [ ] * r for i in range(c) ] 【列表生成器】
3、代碼
from itertools import chain class Solution(object): def matrixReshape(self, nums, r, c):""" :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ if not nums: return nums elif not r or not c: return nums else: h=len(nums) l=len(nums[0]) if h*l != r*c: return nums else: chainnum = chain.from_iterable(nums) result = [] for i in range(r): result.append([]) for j in range(c): result[i].append(next(chainnum)) return result
算法21----重塑矩陣 LeetCode566