-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0957-PrisonCellsAfterNDays.cs
53 lines (47 loc) · 1.49 KB
/
0957-PrisonCellsAfterNDays.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//-----------------------------------------------------------------------------
// Runtime: 244ms
// Memory Usage: 31.9 MB
// Link: https://leetcode.com/submissions/detail/361605384/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0957_PrisonCellsAfterNDays
{
public int[] PrisonAfterNDays(int[] cells, int N)
{
var cache = new Dictionary<string, int>();
var fastForward = false;
while (N > 0)
{
if (!fastForward)
{
var key = string.Join(",", cells);
if (cache.ContainsKey(key))
{
var length = cache[key] - N;
N %= length;
fastForward = true;
}
else
cache.Add(key, N);
}
if (N > 0)
{
cells = NextDay(cells);
N--;
}
}
return cells;
}
private int[] NextDay(int[] cells)
{
int[] newCells = new int[cells.Length];
newCells[0] = 0;
for (int i = 1; i < cells.Length - 1; i++)
newCells[i] = (cells[i - 1] == cells[i + 1]) ? 1 : 0;
newCells[cells.Length - 1] = 0;
return newCells;
}
}
}