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. 如何修改TFS 2013中工作项附件大小限制

    默认情况下,TFS工作项的附件大小限制为4MB.我们可以通过调用TFS提供的Web Service将这个限制调整最高到2GB. 调整这个设置的必备条件是你需要拥有TFS应用层管理员的权限.下面来看看如 ...

  2. 什么是ODBC和JDBC?

    jdbc是使用通过JAVA的数据库驱动直接和数据库相连,而jdbc-odbc连接的是ODBC的数据源,真正与数据库建立连接的是ODBC! 建议使用JDBC直接连接,同时最好使用连接池! JDBC 是 ...

  3. django drf 权限permission

    https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions from django.shortcut ...

  4. 创建可复用的自定义 ASP.NET MVC Helpers

    通常,在ASP.NET MVC项目中App_Code目录下新建.cshtml编写类似下方的代码就能创建自定义的MVC Helper了, 假设文件名为StrHelper.cshtml,那么在别的视图中的 ...

  5. unity 移动物体的方式

    1. 简介 在Unity3D中,有多种方式可以改变物体的坐标,实现移动的目的,其本质是每帧修改物体的position. 2. 通过Transform组件移动物体 Transform 组件用于描述物体在 ...

  6. php实现socket简单的例子

    一.Socket简介 1.socket只不过是一种数据结构 2.使用这个socket数据结构去开始一个客户端和服务器之间的会话 3.服务器是一直在监听准备产生一个新的会话.当一个客户端连接服务端,它就 ...

  7. css3半圆

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

  8. kvm虚拟化之convirt集中管理平台搭建

    情况说明: (1)本文采用OEL6.3x64操作系统,需要有KVM安装环境.(2)convirt2.1.1采用源码方式安装,convirt环境分别两部分,一部分是cms,用于管理kvm/xen虚拟主机 ...

  9. [ActionScript 3.0] as3启动QQ

    import flash.html.HTMLLoader; import flash.net.URLLoader; import flash.net.URLRequest; import flash. ...

  10. 理解 atime,ctime,mtime (下)

    话不多说,开始下篇. # 前言 通过 "理解 atime,ctime,mtime (上)" 我们已经知道了atime 是文件访问时间:ctime是文件权限改变时间:mtime是文件 ...