498. Diagonal Traverse

复制代码
package LeetCode_498

import java.util.*

/**
 * 498. Diagonal Traverse
 * https://leetcode.com/problems/diagonal-traverse/
 *
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]
 * */
class Solution {
    /*
    * solution: scan matrix and insert into queue
    * 1. scan length: m+n-1
    * 2. up right when even index
    * 3. down right when odd index
    * Time complexity:O(mn), Space complexity:O(mn)
    * */
    fun findDiagonalOrder(matrix: Array<IntArray>): IntArray {
        if (matrix == null || matrix.isEmpty()) {
            return IntArray(0)
        }
        val row = matrix.size
        val col = matrix[0].size
        val diagnoals = Array<LinkedList<Int>>(row + col - 1) { LinkedList() }
        for (i in 0 until row) {
            for (j in 0 until col) {
                val key = i + j
                val num = matrix[i][j]
                if (key % 2 == 0) {
                    //up right, insert into head of queue
                    diagnoals[key].offerFirst(num)
                } else {
                    //down right, insert into tail of queue
                    diagnoals[key].offer(num)
                }
            }
        }
        //set the result
        val result = IntArray(row * col)
        var index = 0
        for (item in diagnoals) {
            for (num in item) {
                result[index] = num
                index++
            }
        }
        return result
    }
}
复制代码

 

posted @   johnny_zhao  阅读(64)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-10-13 Dijkstras Algorithm
点击右上角即可分享
微信分享提示