leetcode刷题笔记五十四及五十九 螺旋矩阵和螺旋矩阵II

leetcode刷题笔记五十四及五十九 螺旋矩阵和螺旋矩阵II


源地址:54. 螺旋矩阵

问题描述:

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:

输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

代码补充:

/**
使用按层处理矩阵的方法
以左上角即(0,0)处开始,沿 top -> right -> bottom -> left打印
外层打印完后,修改left、right、top、bottom值,进入内层打印
需要注意的是 要判断处理单层打印情况
进行 top -> right 一侧处理后, 需要判断是否之前打印的是否为单层,若为否,则继续打印,否则打印完成
时间复杂度:O(mn) 空间复杂度:O(1)
*/
import scala.collection.mutable
object Solution {
    def spiralOrder(matrix: Array[Array[Int]]): List[Int] = {
        if (matrix == null || matrix.length == 0 || matrix(0).length == 0) return List()
        
        val res = new mutable.ListBuffer[Int]()
        var left = 0
        var right = matrix(0).length - 1
        var top = 0
        var bottom = matrix.length - 1

        while( left <= right && top <= bottom ){
            for(col <- left to right) res += matrix(top)(col)
            for(row <- top+1 to bottom) res += matrix(row)(right)
            if(left < right && top < bottom){
                for(col <- (left+1 to right-1).reverse) res += matrix(bottom)(col)
                for(row <- (top+1 to bottom).reverse) res += matrix(row)(left)
            }
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        }
        return res.toList
    }
}

源地址:59. 螺旋矩阵 II

问题描述:

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

代码补充:

/**
本题与54题思路遍历过程基本一致,使用left、right、top、bottom计算遍历位置,使用累加变量标记当前位置应放置的数据。注意这里仍然要进行单行判断。
*/
object Solution {
    def generateMatrix(n: Int): Array[Array[Int]] = {
        if (n == 0) return Array()
        val res =  Array.ofDim[Int](n, n)
        val fin = n*n
        var cur = 1
        var left = 0
        var right = n-1
        var top = 0
        var bottom = n-1

        while(left <= right && top <= bottom){
            
            for(i <- left to right){
                res(top)(i) = cur
                cur += 1
            }
            top += 1

            for(i <- top to bottom){
                res(i)(right) = cur
                cur += 1
            }
            right -= 1

            if(top < bottom && left < right){
                for(i <- (left to right).reverse){
                    res(bottom)(i) = cur
                    cur += 1
                }
                bottom -= 1

                for(i <- (top to bottom).reverse){
                    res(i)(left) = cur
                    cur += 1
                }
                left += 1
            }
        }
        return res
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13279757.html