566. Reshape the Matrix

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

大概看了下,想法就是先把这个数组变为一维的,然后建立新的数组,注意一下range的嵌套就行,包括建立多维数组range的应用。

    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        i = len(nums)
        j = len(nums[0])
        if i*j == r*c:
            tmp = [num for row in nums for num in row]
            new = [[0 for x in xrange(c)] for y in xrange(r)]
            for f in range(r):
                for k in range(c):
                    new[f][k] = tmp[f*c+k]
            return new
        else:
            return nums

AC

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,767评论 0 33
  • 还记得那年,大雪纷纷,你穿着红色衣裳在雪中舞蹈。你看见了我,微微一笑。 又是一年大雪纷飞,踏着月光,我又来到了这里...
    薛小宇阅读 599评论 2 1
  • 现在孩子要学的太多了!家长都跟着忙不过来。我们是否要反思一下,为什么让孩子学那么多?为什么要把人生最宝贵的时间,都...
    幸福脑李景林阅读 903评论 0 2
  • 有人说,幸福就是猫吃鱼,狗吃肉,奥特曼专打小怪兽。与我而言,幸福是哪些生活中的小确幸,微不足道却又满心欢喜。 ...
    笨小孩是汤圆阅读 255评论 0 0
  • 今天是3月的最后一天,是结束工作的倒数第三天。平平淡淡地过去了白天,如同这一个月,有期待有欣喜,但总体来说,竟然很...
    麦子和稻子的旅行阅读 209评论 2 2