zoukankan      html  css  js  c++  java
  • leetcode每日一题(2020-06-05):面试题29. 顺时针打印矩阵

    题目描述:
    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

    今日学习:
    1.继续学习mediasoup架构
    2.不要把问题想复杂!

    题解1:

    var spiralOrder = function (matrix) {
      if (matrix.length === 0) return []
      const res = []
      let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
      while (top < bottom && left < right) {
        for (let i = left; i < right; i++) res.push(matrix[top][i])   // 上层
        for (let i = top; i < bottom; i++) res.push(matrix[i][right]) // 右层
        for (let i = right; i > left; i--) res.push(matrix[bottom][i])// 下层
        for (let i = bottom; i > top; i--) res.push(matrix[i][left])  // 左层
        right--
        top++
        bottom--
        left++  // 四个边界同时收缩,进入内层
      }
      if (top === bottom) // 剩下一行,从左到右依次添加
        for (let i = left; i <= right; i++) res.push(matrix[top][i])
      else if (left === right) // 剩下一列,从上到下依次添加
        for (let i = top; i <= bottom; i++) res.push(matrix[i][left])
      return res
    };
    

    题解2:(我原本是这么想的,但是写复杂了没写出来,而且忘记了shift())

    var spiralOrder = function(matrix) {
    if(matrix && matrix.length == 0)
    return [];
    let arr = []
    let matrixCopy = JSON.parse(JSON.stringify(matrix))
    while(matrixCopy.length>0 && matrixCopy[0].length){
        // 1、
        arr.push(...matrixCopy[0]);
        if(matrixCopy.length>0 && matrixCopy[0].length)
        matrixCopy.shift();
        // 2、
        if(matrixCopy.length>0 && matrixCopy[0].length)
        matrixCopy.forEach((item,index) => {
            arr.push(item[item.length-1])
            matrixCopy[index].pop();
        });
        // 3、
        if(matrixCopy.length>0 && matrixCopy[0].length){
            matrixCopy[matrixCopy.length-1].reverse().forEach( item1 => {
                arr.push(item1)
            })
            matrixCopy.length--;
        }   
        // 4、
        if(matrixCopy.length>0 && matrixCopy[0].length)
        for(let i=matrixCopy.length-1; i>0; i--){
            arr.push(matrixCopy[i][0])
            matrixCopy[i].shift();
        }
        
    }
    return arr
    };
    
  • 相关阅读:
    Flink CEP实例及基础应用
    seata 分布式事务
    skywalking 分布式链路追踪
    datax 离线数据同步工具
    rocketmq 消息队列
    Nacos 服务注册
    跨站(cross-site)、跨域(cross-origin)、SameSite与XMLHttpRequest.withCredentials
    读写二进制文件与文本文件
    WPF中通过双击编辑DataGrid中Cell(附源码)
    记一次XML文件读取优化
  • 原文地址:https://www.cnblogs.com/autumn-starrysky/p/13048566.html
Copyright © 2011-2022 走看看