题目
思路
对比我的写法和大佬写法,有几个缺点:
- 一开始没有判空
while循环条件设置不好
var spiralOrder = function(matrix) {
let result =[]
let left =0
let right =matrix[0].length -1
let top =0
let bottom =matrix.length -1
let num =1
let total =matrix.length * matrix[0].length
while(num<=total){
for(let i =left;i<=right;i++){
result.push(matrix[top][i])
num++
}
if(num>total)break
top++
for(let i =top;i<=bottom;i++){
result.push(matrix[i][right])
num++
}
if(num>total)break
right--
console.log(left,right)
for(let i =right;i>=left;i--){
result.push(matrix[bottom][i])
num++
}
if(num>total)break
bottom--
for(let i =bottom;i>=top;i--){
result.push(matrix[i][left])
num++
}
if(num>total)break
left++
}
return result
};
结合我的理解和官方的最终代码
var spiralOrder = function(matrix) {
// 虽然这道题不用判断,但我没有这个思维
if(!matrix.length || !matrix[0].length) return []
let result =[]
let left =0
let right =matrix[0].length -1
let top =0
let bottom =matrix.length -1
while(left<=right &&top<=bottom){
// 左闭右闭,比官方解答里一部分左闭右闭一部分左闭右开好理解。
for(let i =left;i<=right;i++){
result.push(matrix[top][i])
}
for(let i =top+1;i<=bottom;i++){
result.push(matrix[i][right])
}
// 最重要就是在从右往左和从下往上的时候,再判断一下是否超出边界。
if(left<right &&top<bottom){
for(let i =right-1;i>=left;i--){
result.push(matrix[bottom][i])
}
for(let i =bottom-1;i>=top+1;i--){
result.push(matrix[i][left])
}
}
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1]
}
return result
};
原官方代码
var spiralOrder = function(matrix) {
if (!matrix.length || !matrix[0].length) {
return [];
}
const rows = matrix.length, columns = matrix[0].length;
const order = [];
let left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (let column = left; column <= right; column++) {
order.push(matrix[top][column]);
}
for (let row = top + 1; row <= bottom; row++) {
order.push(matrix[row][right]);
}
if (left < right && top < bottom) {
for (let column = right - 1; column > left; column--) {
order.push(matrix[bottom][column]);
}
for (let row = bottom; row > top; row--) {
order.push(matrix[row][left]);
}
}
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1];
}
return order;
};