Prison Cells After N Days
Input:
cells =
[0,1,0,1,1,0,0,1]
, N =
7
Output:
[0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
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]Analysis & Solution
Brute-force Simulation
时间优化:找pattern
时间优化才是重点,不做不必要的空间优化可以让代码更简洁:
假设已经找到循环的Pattern周期为14之后,可以用如下方法:
Reference
Last updated