forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prison-cells-after-n-days.cpp
58 lines (54 loc) · 1.52 KB
/
prison-cells-after-n-days.cpp
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
54
55
56
57
58
// Time: O(1)
// Space: O(1)
class Solution {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
for (N = (N - 1) % 14 + 1; N > 0; --N) {
vector<int> cells2(8);
for (int i = 1; i < 7; ++i) {
cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]);
}
cells = move(cells2);
}
return cells;
}
};
// Time: O(1)
// Space: O(1)
class Solution2 {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
unordered_map<vector<int>, int, VectorHash<int>> lookup;
while (N) {
lookup[cells] = N--;
vector<int> cells2(8);
for (int i = 1; i < 7; ++i) {
cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]);
}
cells = move(cells2);
if (lookup.count(cells)) {
N %= lookup[cells] - N;
break;
}
}
while (N--) {
vector<int> cells2(8);
for (int i = 1; i < 7; ++i) {
cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]);
}
cells = move(cells2);
}
return cells;
}
private:
template<typename T>
struct VectorHash {
size_t operator()(const std::vector<T>& v) const {
size_t seed = 0;
for (const auto& i : v) {
seed ^= std::hash<T>{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
return seed;
}
};
};