题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
今日学习:
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
};