首页 > 其他分享 >leetcode 766. Toeplitz Matrix

leetcode 766. Toeplitz Matrix

时间:2023-05-30 18:05:57浏览次数:39  
标签:return matrix List 766 len range True leetcode Matrix

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
 

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512

In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True.

Example 2:

Input: matrix = [[1,2],[2,2]]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.

Note:

  1. matrix will be a 2D array of integers.
  2. matrix will have a number of rows and columns in range [1, 20].
  3. matrix[i][j] will be integers in range [0, 99].
class Solution(object):
    def isToeplitzMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: bool
        """
        """
1234
5123
9512
        #judge all matrix[i][j]==matrix[i-1][j-1]
        
        row = len(matrix)
        col = len(matrix[0])
        for i in range(1, row):
            for j in range(1, col):
                if matrix[i][j] != matrix[i-1][j-1]:
                    return False
        return True
        """
        
        return all(matrix[i][j] == matrix[i+1][j+1] for i in range(len(matrix)-1) for j in range(len(matrix[0])-1))

        """
>>> all([1,2,3])
True
>>> all([1,2,3,0])
False
>>> print([i*j for i in range(1,3) for j in range(9,7,-1)])
[9, 8, 18, 16]
        """

 另外一种利用切片思路:

class Solution(object):
    def isToeplitzMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: bool
        """
        for i in range(len(matrix)-1):
            if matrix[i][:-1]!=matrix[i+1][1:]: 
                return False
        return True

 

标签:return,matrix,List,766,len,range,True,leetcode,Matrix
From: https://blog.51cto.com/u_11908275/6381138

相关文章

  • 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......
  • leetcode 657. Judge Route Circle
    Initially,thereisaRobotatposition(0,0).Givenasequenceofitsmoves,judgeifthisrobotmakesacircle,whichmeansitmovesbackto theoriginalplace.Themovesequenceisrepresentedbyastring.Andeachmoveisrepresentbyacharacter.The......