1.嵌套数组的环形遍历
嵌套数组的环形遍历
题目
嵌套数组的环形遍历,简单讲就是
[[1,2,3],[4,5,6],[7,8,9]]
按照[1, 2, 3, 6, 9, 8, 7, 4, 5]
遍历,题目是 m*n 的矩阵
示例
// 输入一个arr
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
// 输出结果newArr
newArr = [1, 2, 3, 6, 9, 8, 7, 4, 5];
提示
DETAILS
- 定义边界:使用四个变量来定义当前的边界:top、bottom、left 和 right。
- 循环遍历: 从 top 行遍历从 left 到 right 的元素。 从 right 列遍历从 top + 1 到 bottom 的元素(如果 top < bottom)。 从 bottom 行遍历从 right - 1 到 left - 1 的元素(如果 top < bottom)。 从 bottom - 1 行遍历从 bottom 到 top 的元素(如果 left < right)。
- 更新边界:每次遍历后,更新 top、bottom、left 和 right 的值。
- 结束条件:当 top > bottom 或 left > right 时,停止遍历。
参考答案
DETAILS
<script>
// 测试用例
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
function spiralOrder(arr) {
if (arr.length == 0) return [];
const result = []
// 上,左,下,右
let top = 0
let left = 0
let bottom = arr.length - 1
let right = arr[0].length - 1
while (top <= bottom && left <= right) {
// 从左到右判断完然后top加1
for (let i = left; i <= right; i++) {
result.push(arr[top][i])
}
top++;
// 从上到下边遍历
for (let i = top; i <= bottom; i++) {
result.push(arr[i][right])
}
right--;
// 从右到到左边遍历
if (top <= bottom) {
for (let i = right; i >= left; i--) {
result.push(arr[bottom][i]);
}
bottom--;
}
// 从下到上遍历左边
if (left <= right) {
for (let i = bottom; i >= top; i--) {
result.push(arr[i][left]);
}
left++;
}
}
return result;
}
console.log(spiralOrder(arr));
</script>