LeetCode 题解工作台

N 天后的牢房

监狱中 8 间牢房排成一排,每间牢房可能被占用或空置。 每天,无论牢房是被占用或空置,都会根据以下规则进行变更: 如果一间牢房的两个相邻的房间都被占用或都是空的,那么该牢房就会被占用。 否则,它就会被空置。 注意 :由于监狱中的牢房排成一行,所以行中的第一个和最后一个牢房不存在两个相邻的房间。 给你…

category

4

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

监狱中 8 间牢房排成一排,每间牢房可能被占用或空置。

每天,无论牢房是被占用或空置,都会根据以下规则进行变更:

  • 如果一间牢房的两个相邻的房间都被占用或都是空的,那么该牢房就会被占用。
  • 否则,它就会被空置。

注意:由于监狱中的牢房排成一行,所以行中的第一个和最后一个牢房不存在两个相邻的房间。

给你一个整数数组 cells ,用于表示牢房的初始状态:如果第 i 间牢房被占用,则 cell[i]==1,否则 cell[i]==0 。另给你一个整数 n

请你返回 n 天后监狱的状况(即,按上文描述进行 n 次变更)。

 

示例 1:

输入:cells = [0,1,0,1,1,0,0,1], n = 7
输出:[0,0,1,1,0,0,0,0]
解释:下表总结了监狱每天的状况:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]

示例 2:

输入:cells = [1,0,0,1,0,0,1,0], n = 1000000000
输出:[0,0,1,1,1,1,1,0]

 

提示:

  • cells.length == 8
  • cells[i]01
  • 1 <= n <= 109
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Will ask if the solution handles very large N efficiently without full simulation.

  • question_mark

    May probe about how to detect repeating patterns and cycle lengths.

  • question_mark

    Could question the bit manipulation optimization for faster state updates.

warning

常见陷阱

外企场景
  • error

    Forgetting to treat the first and last cells as always vacant the next day.

  • error

    Overwriting the current day's cell values before computing neighbors, causing incorrect results.

  • error

    Failing to detect cycles, leading to excessive computation for large N values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Prison cells of arbitrary length instead of 8, requiring generalized neighbor rules.

  • arrow_right_alt

    Changing the state transition rule to different neighbor conditions, affecting cycle detection.

  • arrow_right_alt

    Return the number of days until the cells first repeat instead of final state after N days.

help

常见问题

外企场景

N 天后的牢房题解:数组·哈希·扫描 | LeetCode #957 中等