算法题:找出数字所在行和列

今天群里有人贴了个算法题出来,说不会做,然后就有了此文。

我的解答

初次解答

function getRowAndCol(num) {
  const rows = [[1, 2, 3, 4, 5]];
  let fnName = 'push';
  for (let i = 0, current = 5; current < num; i++) {
    if (i % 5 === 0) {
      fnName = fnName === 'push' ? 'unshift' : 'push';
      const row = [];
      rows.push(row);
      row[fnName]('');
    } else {
      const row = rows[rows.length - 1];
      row[fnName](++current);
    }
  }

  const lastRow = rows[rows.length - 1];
  for (let i = lastRow.length; i < 5; i++) {
    lastRow[fnName]('');
  }
  console.log(rows);

  const map = ['A', 'B', 'C', 'D', 'E'];
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
    const row = rows[rowIndex];
    for (let colIndex = 0; colIndex < row.length; colIndex++) {
      const col = row[colIndex];
      if (col === num) {
        return [rowIndex + 1, map[colIndex]];
      }
    }
  }
  return [];
}
const [row, col] = getRowAndCol(30);
console.log(`在第${row}行${col}列`);

输出

优化

优化思路:

  1. 后面不需要查找整个rows,只要找最后一行就行了。
  2. 不需要生成具体的数据结构,太浪费空间了;同1,只要计算出最后一行的结构就能推断出位置。

最终版

function getRowAndCol(num) {
  if (num < 1) {
    return [];
  }
  const map = ['A', 'B', 'C', 'D', 'E'];
  if (num < 6) {
    return [1, map[num - 1]];
  }
  const row = Math.ceil((num - 5) / 4);
  const col = num - ((row - 1) * 4 + 5);

  return [row + 1, map[row % 2 === 0 ? col : 4 - col]];
}
const num = Number(process.argv[2]);
const [row, col] = getRowAndCol(num);
console.log(`在第${row}行${col}列`);

// for(let i = 1;i<20;i++) {
//     const [row, col] = getRowAndCol(i);
//     console.log(`${i}在第${row}行${col}列`);
// }

群友的解答


评论

0 / 800
全部评论()