zoukankan      html  css  js  c++  java
  • leetcode-766-Toeplitz 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].

     

    要完成的函数:

    bool isToeplitzMatrix(vector<vector<int>>& matrix) 

     

    说明:

    1、这道题题意很清晰,给定一个矩阵,判断矩阵上的所有对角线,每一条对角线上的元素值是不是都相等,比如题目中给的例1,就是一个满足条件的矩阵。最后返回true或者false,表示矩阵满不满足条件。

    2、笔者最开始觉得这道题又是比较麻烦的题目,又要设置行i列j的条件限制,然后一一比较元素值。但后来重新扫了一遍题目叙述,发现可以逐行地搬下来比较,没有被比较到的元素,也刚好就是不用比较的。

    举个例子,第一行除了最后一个之外的其余元素,都搬下来与第二行的元素进行比较,而第二行第一个元素不会被比较到,也刚好就是不用比较的,只需要之后跟第三行比较。

    所以,逻辑清晰,代码如下:

        bool isToeplitzMatrix(vector<vector<int>>& matrix) 
        {
            int row=matrix.size(),col=matrix[0].size();
            int i=0,j;
            while(i<row-1)//这里是row-1,最后一行不用再比较
            {
                j=0;
                while(j<col-1)//col-1,每行最后一个元素不用比较
                {
                    if(matrix[i][j]!=matrix[i+1][j+1])
                        return false;
                    j++;
                }
                i++;
            }
            return true;
        }
    

    上述代码实测20ms,beats 77.39% of cpp submissions。

  • 相关阅读:
    经典算法系列二-归并排序
    经典算法系列一-快速排序
    u-boot,linux,文件系统移植笔记1
    ARM函数调用时参数传递规则
    内核移植 nand分区
    LINUX的patch文件打patch
    idea插件使用
    socket通信同步通信,异步通信
    今天学了一个很简易的测试数据库是否连接成功
    wpf中TreeView的使用
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9041091.html
Copyright © 2011-2022 走看看