Reshape the Matrix
可以用额外空间,这样逻辑的思考没有那么复杂了,当然不用额外空间也可以做
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
n = len(nums)
if not n:
return []
m = len(nums[0])
if not m:
return []
if n * m != r * c:
return nums
nums = reduce(operator.add, nums)
result = []
cur = 0
for i in xrange(r):
result.append(nums[cur : cur + c])
cur += c
return result
理论上没有额外空间的算法
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
n = len(nums)
if not n:
return []
m = len(nums[0])
if not m:
return []
if n * m != r * c:
return nums
count = 0
result = [[0] * c for _ in xrange(r)]
for i in xrange(n):
for j in xrange(m):
result[count / c][count % c] = nums[i][j]
count += 1
return result