美文网首页
[python] 2019-02-28

[python] 2019-02-28

作者: 原来是酱紫呀 | 来源:发表于2019-02-28 23:06 被阅读0次

.766. Toeplitz Matrix

note: enumerate()
all() 与any()


766. Toeplitz Matrix

1) description

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:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

2) solution

class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        groups={}
        for i ,r in enumerate(matrix):
            for j, v in enumerate(r):
                if i-j not in groups:
                    groups[i-j] = v
                elif groups[i-j] !=v:
                    return False
        return True

other's

class Solution(object):
    def isToeplitzMatrix(self, matrix):
        return all(r == 0 or c == 0 or matrix[r-1][c-1] == val
                   for r, row in enumerate(matrix)
                   for c, val in enumerate(row))
class Solution:
    def isToeplitzMatrix(self, matrix: 'List[List[int]]') -> 'bool':
        n = len(matrix[0]) - 1
        for i in range(len(matrix) - 1):
            if matrix[i][0:n] != matrix[i+1][1:]:
                return False
        return True
    ```

相关文章

网友评论

      本文标题:[python] 2019-02-28

      本文链接:https://www.haomeiwen.com/subject/pqakuqtx.html