首页 > 其他分享 >leetcode 566. Reshape the Matrix

leetcode 566. Reshape the Matrix

时间:2023-05-30 18:06:05浏览次数:49  
标签:return matrix nums Reshape 566 original reshape leetcode row

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.

Example 1:

Input: 
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.

Example 2:

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.

 

 计算数组下标是关键!

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        row = len(nums)
        col = len(nums[0])
        if row*col != r*c:
            return nums
        ans = [0]*r
        for i in range(0, r):
            ans[i] = [0]*c
        for j in range(0, c*r):                   
            ans[j/c][j%c] = nums[j/col][j%col]
        return ans

 直接调用numpy的函数:

import numpy as np

class Solution(object):
    def matrixReshape(self, nums, r, c):
        try:
            return np.reshape(nums, (r, c)).tolist()
        except:
            return nums

 

标签:return,matrix,nums,Reshape,566,original,reshape,leetcode,row
From: https://blog.51cto.com/u_11908275/6381137

相关文章

  • leetcode 766. Toeplitz Matrix
    AmatrixisToeplitzifeverydiagonalfromtop-lefttobottom-righthasthesameelement.NowgivenanMxNmatrix,return True ifandonlyifthematrixisToeplitz. Example1:Input:matrix=[[1,2,3,4],[5,1,2,3],[9,5,1,2]]Output:TrueExplanation:12......
  • leetcode 575. Distribute Candies
    Givenanintegerarraywithevenlength,wheredifferentnumbersinthisarrayrepresentdifferentkindsofcandies.Eachnumbermeansonecandyofthecorrespondingkind.Youneedtodistributethesecandiesequallyinnumbertobrotherandsister.Retur......
  • leetcode 412. Fizz Buzz
    Writeaprogramthatoutputsthestringrepresentationofnumbersfrom1ton.Butformultiplesofthreeitshouldoutput“Fizz”insteadofthenumberandforthemultiplesoffiveoutput“Buzz”.Fornumberswhicharemultiplesofboththreeandfiveoutp......
  • leetcode 669. Trim a Binary Search Tree
    GivenabinarysearchtreeandthelowestandhighestboundariesasLandR,trimthetreesothatallitselementsliesin[L,R](R>=L).Youmightneedtochangetherootofthetree,sotheresultshouldreturnthenewrootofthetrimmedbinarys......
  • leetcode 500. Keyboard Row
    GivenaListofwords,returnthewordsthatcanbetypedusinglettersofalphabetononlyonerow'sofAmericankeyboardliketheimagebelow.  Example1:Input:["Hello","Alaska","Dad","Peace"]Output:[&q......
  • leetcode 344. Reverse String
    Writeafunctionthattakesastringasinputandreturnsthestringreversed.Example:Givens="hello",return"olleh".classSolution(object):defreverseString(self,s):""":types:str......
  • leetcode 557. Reverse Words in a String III
    Givenastring,youneedtoreversetheorderofcharactersineachwordwithinasentencewhilestillpreservingwhitespaceandinitialwordorder.Example1:Input:"Let'stakeLeetCodecontest"Output:"s'teLekatedoCteeLtsetno......
  • leetcode 476. Number Complement
    Givenapositiveinteger,outputitscomplementnumber.Thecomplementstrategyistoflipthebitsofitsbinaryrepresentation.Note:Thegivenintegerisguaranteedtofitwithintherangeofa32-bitsignedinteger.Youcouldassumenoleadingzerobiti......
  • leetcode 561. Array Partition I
    Givenanarrayof2nintegers,yourtaskistogrouptheseintegersintonpairsofinteger,say(a1,b1),(a2,b2),...,(an,bn)whichmakessumofmin(ai,bi)forallifrom1tonaslargeaspossible.Example1:Input:[1,4,3,2]Output:4Explanation:......
  • leetcode 728. Self Dividing Numbers
    Aself-dividingnumberisanumberthatisdivisiblebyeverydigititcontains.Forexample,128isaself-dividingnumberbecause128%1==0,128%2==0,and128%8==0.Also,aself-dividingnumberisnotallowedtocontainthedigitzero.Givenal......