498_Diagonal-Traverse

Description

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]

Explanation:

Note:

  1. The total number of elements of the given matrix will not exceed 10,000.

Solution

Java solution

class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return new int[0];
} int m = matrix.length, n = matrix[0].length; int[] res = new int[m * n];
int row = 0, col = 0, d = 1;
for (int i = 0; i < m*n; i++) {
res[i] = matrix[row][col]; row -= d;
col += d; // lower border
if (row >= m) {
row -= 1;
col += 2;
d = -d;
} // right border
if (col >= n) {
col -= 1;
row += 2;
d = -d;
} // upper border
if (row < 0) {
row = 0;
d = -d;
} // left border
if (col < 0) {
col = 0;
d = -d;
}
} return res;
}
}

Runtime: 7 ms. Your runtime beats 97.45 % of java submissions.

Python solution 1

class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if matrix == []:
return []
m, n = len(matrix), len(matrix[0])
coordinates = [(i, j) for i in range(m) for j in range(n)]
coordinates.sort(key=lambda x: sum(x) * max(m, n) - x[sum(x) % 2])
return [matrix[x][y] for x, y in coordinates]

Runtime: 164 ms. Your runtime beats 37.74 % of python3 submissions.

Python solution 2

class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
entries = [(i + j, (j, i)[(i ^ j) & 1], val)
for i, row in enumerate(matrix)
for j, val in enumerate(row)]
return [e[2] for e in sorted(entries)]

Runtime: 136 ms. Your runtime beats 77.36 % of python3 submissions.

Python solution 3

class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
m, n = len(matrix), len(matrix and matrix[0])
return [matrix[i][d-i]
for d in range(m+n-1)
for i in range(max(0, d-n+1), min(d+1, m))[::d%2*2-1]]

Runtime: 148 ms. Your runtime beats 59.43 % of python3 submissions.

498_Diagonal-Traverse的更多相关文章

  1. CSharp Algorithm - How to traverse binary tree by breadth (Part II)

    /* Author: Jiangong SUN */ Here I will introduce the breadth first traversal of binary tree. The pri ...

  2. node to traverse cannot be null!

    严重: Servlet.service() for servlet springmvc threw exception java.lang.IllegalArgumentException: node ...

  3. [Swift]LeetCode498. 对角线遍历 | Diagonal Traverse

    Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal ...

  4. 6.ZigZag Conversion(Graph, traverse)

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  5. 递归中traverse小人 & dc女王的区别

    TRAVERSE 是一个小人, 拿着一个记事本, 顺着二叉树走, 走过一个, 在本子上面记下来 DIVIDE & CONQUER 是女王接到这个任务, 找两个小弟A和B, 让A和B先去收集, ...

  6. Traverse the dict in Python

    We usually use the following 2 ways to traverse a dict: 1: for d in dic 2: for d in dic.keys() Which ...

  7. 814. Binary Tree Pruning(leetcode) (tree traverse)

    https://leetcode.com/contest/weekly-contest-79/problems/binary-tree-pruning/ -- 814 from leetcode tr ...

  8. Traverse an expression tree and extract parameters

    Traverse an expression tree and extract parameters   I think as you've said that using ExpressionVis ...

  9. @babel/traverse 使用方法小记

    @babel/traverse 官网: https://babeljs.io/docs/en/babel-traverse github:https://github.com/babel/babel/ ...

  10. 【LeetCode】498. Diagonal Traverse 解题报告(Python)

    [LeetCode]498. Diagonal Traverse 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: htt ...

随机推荐

  1. 微信小程序web-view之动态加载html页面

    官方推出的web-view方便了很多开发人员. 我们在做的时候,经常会想到写一个小程序的page然后通过动态加载web-view的形式来完成其他功能页面的开发. 之前研究web-view的时候发现网上 ...

  2. 关于Unity中MonoBehaviour的构造函数

    关于Unity中MonoBehaviour的构造函数 在学习Unity MVVM UI框架的时候,一不小给一个继承自MonoBehaviour类的子类编写了自定义构造函数,结果调Bug调了两个钟,特此 ...

  3. django drf 自定义jwt用户验证逻辑

    新建Backend类 from django.contrib.auth.backends import ModelBackend from django.shortcuts import render ...

  4. 8-网络请求之http

    本篇博客对应视频讲解 回顾 上一篇讲了Linq的使用,大家自己上手实践之后,相信一定会感到非常快捷方便.更多详细的内容还是需要自己去阅读官方文档. 今天要讲网络请求中的http请求,这也是在编程当中经 ...

  5. 多个音频audio2

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. vue 生命周期 笔记

    生命周期:一个组件从创建到销毁的这个过程叫做生命周期 生命周期钩子函数   1.组件从创建到销毁的过程 1.创建前 创建后 2.挂载前 挂载后 3.更新前 更新后 4.销毁前 销毁后 beforeCr ...

  7. 初探APT 攻击

    作者:joe       所属团队:Arctic Shell 本文编写参考: https://www.freebuf.com/vuls/175280.html https://www.freebuf. ...

  8. 考试题 T2

    题意分析 首先 要求起点终点不连通 再结合数据范围 就是最小割了 首先我们可以建一个图出来 如果\(x\)可以到\(y\)的话 那么我们就从\(x\)向\(y\)连一条代价为\(h[x]-h[y]+1 ...

  9. 手动启动 oracle 服务

      手动启动 Oracle 服务 为了学习,我们常常会在个人PC上安装 Oracle 数据库,这大大影响了计算机的运行速度,尤其是计算机开机速度,如果 Oracle 使用频率并不是非常高,我们可以禁止 ...

  10. 【SpringBoot+Mybatis+thymeleaf报错】Error resolving template "XXX", template might not exist or might not be accessible by any of the configured

    解决方法一: 原因:在使用springboot的过程中,如果使用thymeleaf作为模板文件,则要求HTML格式必须为严格的html5格式,必须有结束标签,否则会报错. 在application.y ...