Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
prison-cells-after-n-days.cpp 1.52 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-12-16 15:59 +08:00 . Update prison-cells-after-n-days.cpp
// 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;
}
};
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助