There are 8 prison cells in a row, and each cell is either occupied or vacant.

Each day, whether the cell is occupied or vacant changes according to the following rules:

  • If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
  • Otherwise, it becomes vacant.

(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)

We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.

Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)

example

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]

题目要求:8个(0,1)一排,两边相同中间变1,两边不同中间变0。问N次后的数组样子。

思路1:使用字典记录每一个过程和遍历时的N,如果有重复直接取模。减少运算量。

  class Solution {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
unordered_map<string, int> map;
string firstcell = "";
for (int i = ; i<cells.size(); i++) {
firstcell += to_string(cells[i]);
}
while (N != ) {
if (map.count(firstcell))
N %= map[firstcell] - N;
if(N == ) break;
string nextstr = "";
for (int i = ; i < ; i++) {
nextstr += firstcell[i - ] == firstcell[i + ] ? "" : "";
}
nextstr = "" + nextstr + "";
//cout << nextstr << endl;
map[firstcell] = N;
firstcell = nextstr;
N--;
}
vector<int> ret;
for (int i = ; i<firstcell.size(); i++) {
if (firstcell[i] == '') ret.push_back();
else ret.push_back();
}
return ret;
}
};

最新文章

  1. 转:什么是即时编译(JIT)!?OpenJDK HotSpot VM剖析
  2. MYSQL #1064错误
  3. 使用 JavaScript
  4. spring对事物的支持
  5. WindowsPhone8SDK重装后设计器加载异常的处理办法
  6. 转载:JAVA 正则表达式 (超详细)
  7. asp.net 获取IP地理位置的几个主要接口
  8. 前两篇转载别人的精彩文章,自己也总结一下python split的用法吧!
  9. python callable 函数
  10. Selenium学习资源和网站
  11. asp.net mvc前台显示带htm标签的解决办法(Razor —@Html.Raw())
  12. ThreadLocal说明
  13. Java学习之代码块(静态,构造代码块,构造方法)执行顺序
  14. 【BZOJ3925】[ZJOI2015]地震后的幻想乡(动态规划)
  15. PAT Basic 1007
  16. 使用python-aiohttp爬取今日头条
  17. sencha touch Model validations 自定义验证 二选一输入验证、重复验证、时间验证、比较验证、条件验证(2015-1-14)
  18. IQ调制原理
  19. 一次scrapy成功停止的信息
  20. 在 Linux 平台中调试 C/C++ 内存泄漏方法(转)

热门文章

  1. Django安装和介绍
  2. STM32——CAN协议帧的标准格式和扩展格式与优先级的关系
  3. 单元测试框架之unittest(一)
  4. bat 提示窗口,带换行
  5. Ubuntu安装截图软件shutter
  6. [转载]ac mysql 无法远程连接
  7. 【线段树 矩阵乘法dp】8.rseq
  8. [Cypress] Use the Most Robust Selector for Cypress Tests
  9. EXE中释放DLL中分配的内存
  10. not(expr|ele|fn)从匹配元素的集合中删除与指定表达式匹配的元素