美文网首页leetcode --- js版本
leetcode-Medium-22期-数组-Spiral Ma

leetcode-Medium-22期-数组-Spiral Ma

作者: 石头说钱 | 来源:发表于2019-03-24 10:57 被阅读0次

题目

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

  • Example 1
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

  • Example 2
Input:
[
 [1, 2, 3, 4],
 [5, 6, 7, 8],
 [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

  • 思路
关键在于边界条件判断
可以理解为圆圈套圆圈
  • 解法
var spiralOrder = (matrix) => {
  let height = matrix.length
  let width = matrix[0] ? matrix[0].length : 0;
  let totalEle = height*width
  let res = []
  let i = 0;
  let count = 0
  while(count < totalEle){
    // 顶部元素
    if(count < totalEle){
      for(let j = i + 0; j < width - i; j++){
        res.push(matrix[i][j])
        count++
      }
    }
    if(count < totalEle){
         // 右边元素
      for( let j = i + 1; j <height - i ; j++){
        res.push(matrix[j][width - i - 1])
        count++
      }
    }
    if(count < totalEle){
          // 底部元素
      for( let j = width - 2 - i; j >=i; j--){ //j>=i不是j>=0
        res.push(matrix[height - i - 1][j])
        count++
      }
    }
    if(count < totalEle){
       //左边元素
      for( let j = height - 2 - i; j >i; j--){
        res.push(matrix[j][i])
        count++
      }
    }
 
    i++
  }
  return res
}

相关文章

网友评论

    本文标题:leetcode-Medium-22期-数组-Spiral Ma

    本文链接:https://www.haomeiwen.com/subject/scwevqtx.html