554.砖墙
链接:554.砖墙
难度:Medium
标签:数组、哈希表
简介:你需要找出怎样画才能使这条线 穿过的砖块数量最少 ,并且返回 穿过的砖块数量 。
题解 1 - typescript
- 编辑时间:2021-05-02
- 执行用时:136ms
- 内存消耗:45.2MB
- 编程语言:typescript
- 解法介绍:统计每个边界的空数。
function leastBricks(wall: number[][]): number {
  const rowLen = wall.length;
  const size = wall[0].reduce((total, cur) => total + cur, 0);
  if (wall.every(row => row.length === 1)) return rowLen;
  const map: Record<number, number> = {};
  for (const row of wall) {
    let sum = -1;
    for (const col of row) {
      sum += col;
      map[sum] = 1 + (map[sum] ?? 0);
    }
  }
  Reflect.deleteProperty(map, size - 1);
  return rowLen - Math.max(...Object.values(map));
}