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. [Elixir006]CSV(Comma-separated values)处理

    1. CSV文件格式是什么 CSV有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本).纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数 ...

  2. solr特点六: DIH (从数据源导入数据)

    在这个结构化数据和非结构化数据的数量都很庞大的年代,经常需要从数据库.XML/HTML 文件或其他数据源导入数据,并使数据可搜索.过去,要编写自定义代码才能创建到数据库.文件系统或 RSS 提要的自定 ...

  3. C++的一些知识点摘抄(创建基本类 高级类)

    问:对象有多大? 答:对象占据的内存量取决于其成员变量的长度,类函数不占据为对象分配的内容. 有些编译器在内存中对齐变量,这导致2字节变量实际占用的内存多于2字节. 问:为何不应将所有成员数据声明为公 ...

  4. NETCore调用AD域验证

    一.添加引用 System.DirectoryServices System.DirectoryServices.AccountManagement 二.验证代码 声明域 string domainN ...

  5. WPF 新手引导

    参考了https://www.cnblogs.com/ZXdeveloper/p/8391864.html,自己随便实现了一个,记录下,比较丑 <Window x:Class="Use ...

  6. django系列8.2--django的中间件流程

    Django请求流程图 请求到达中间件之后,先按照正序执行每个注册中间件的process_reques方法,process_request方法返回的值是None,就依次执行,如果返回的值是HttpRe ...

  7. Android 音视频开发入门指南

    Android 音视频从入门到提高 —— 任务列表 http://blog.51cto.com/ticktick/1956269(以这个学习为基础往下面去学习) Android 音视频开发学习思路-- ...

  8. 微信小程序转发商品的详情页 + 转发功能(传参)

    1.微信小程序转发传参,利用的还是onShareAppMessageapi 2.利用的还有json转换 JSON 是用于存储和传输数据的格式. JSON 通常用于服务端向网页传递数据 函数 描述JSO ...

  9. “全栈2019”Java第一百章:局部内部类可以实现接口吗?

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  10. Centos 7.x 安装配置tomcat-8过程梳理

    ----------注意CentOS7.x中的selinux和firewalld都关闭.而且一.二.三部分都是独立的,所以发现8081和8080端口时不要慌哦. 原创,朋友们转载时请著名出处. 一.安 ...