跳到主要内容

2624.蜗牛排序

链接:2624.蜗牛排序
难度:Medium
标签:
简介:请你编写一段代码为所有数组实现 snail(rowsCount,colsCount) 方法,该方法将 1D 数组转换为以蜗牛排序的模式的 2D 数组。

题解 1 - typescript

  • 编辑时间:2023-04-23
  • 执行用时:212ms
  • 内存消耗:55.8MB
  • 编程语言:typescript
  • 解法介绍:模拟,利用方向数组控制方向。
declare global {
interface Array<T> {
snail(rowsCount: number, colsCount: number): number[][];
}
}
Array.prototype.snail = function (rowsCount: number, colsCount: number): number[][] {
if (rowsCount * colsCount !== this.length) return [];
const res: number[][] = new Array(rowsCount).fill(0).map(_ => new Array(colsCount).fill(0));
const dirs = [
[0, rowsCount, 1],
[rowsCount - 1, -1, -1],
];
let idx = 0;
for (let j = 0; j < colsCount; j++) {
const dir = dirs[j % 2];
for (let i = dir[0]; i != dir[1]; i += dir[2]) {
res[i][j] = this[idx++];
}
}
return res;
};