[54] 螺旋矩阵 js

题目描述:给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素

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

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

解题思路:

按照顺时针一行一列,往里收缩

解法一:

javascript 复制代码
function spiralOrder(matrix) {
    let left = 0;
    let right = matrix[0].length - 1;
    let top = 0;
    let bottom = matrix.length - 1 ;
    let res = [];


   // 按照顺时针进行输出,规定好收缩边界
    while (left <= right && top <= bottom) {
        // 第一行
        for (let i = left; i <= right; i++) {
            res.push(matrix[top][i]);
        };
        top++;
        // 最后一列
        for (let i = top; i <= bottom; i++) {
            res.push(matrix[i][right]);
        };
        right--;
        // 最后一行

        if (top <= bottom && left <= right) {
            for (let i = right; i >= left; i--) {
                res.push(matrix[bottom][i]);
            }
            bottom--;

            // 第一列
            for (let i = bottom; i >= top; i--) {
                res.push(matrix[i][left]);
            }
            left++;
        }
        
    }
    return res;

    
};

用时:

// Your runtime beats 30.54 % of typescript submissions

// Your memory usage beats 84.1 % of typescript submissions (42.1 MB)

相关推荐
林恒smileZAZ1 小时前
Vue<前端页面版本检测>
前端·javascript·vue.js
2301_764441335 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI5 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly5 小时前
ABC 453 个人题解
算法·题解·atcoder
我是Superman丶5 小时前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
玉树临风ives5 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1236 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
Huanzhi_Lin6 小时前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
fengfuyao9856 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神7 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法