leetcode吧 关注:1,123贴子:2,456
  • 13回复贴,共1

957. Prison Cells After N Days 是不是位运算? 偷看了别人算法

只看楼主收藏回复

有八个牢房。有空的,也有有犯人的。
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.)
这个表示牢房的数组 cells, cells[i]==1 有人 cells[i]==0 没人
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.
有最初牢房的状态。求N天以后牢房是怎么安排的。
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7Output: [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]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]
超时的算法~~ 算了近一分钟才跳结果。当然在leetcode那边就直接down了。
public int[] PrisonAfterNDays(int[] cells, int N) {
if(N==0) return cells;
while(N>0){
cells=PassDay(cells);
N=N-1;
}
return cells;
}
private int[] PassDay(int[] cells){
int[] res=new int[8];
for(int i=1;i<7;i++){
if(cells[i-1]==cells[i+1]){
res[i]=1;
}else{
res[i]=0;
}
}
return res;
}
如果是位运算,我就缴械投降了。。。 感觉位运算要漂移到电子电路领域。


IP属地:上海1楼2018-12-19 18:16回复
    每过一天存一次,等什么时候出现重复了计算一下循环周期得出第N天的情况


    IP属地:河北2楼2018-12-23 21:51
    收起回复
      2025-08-24 00:39:10
      广告
      不感兴趣
      开通SVIP免广告
      var prisonAfterNDays = function(cells, N) {
      var res=[...cells];
      for(var i=1;i<=N;i++){
      var temp=[...res];
      for(var j=0;j<cells.length;j++){
      if(j==0||j==cells.length-1){
      temp[j]=0;
      }
      else{
      if((res[j-1]==1&&res[j+1]==1)||(res[j-1]==0&&res[j+1]==0)){
      temp[j]=1;
      }
      else{
      temp[j]=0;
      }
      }
      }
      console.log("第"+i+"天:",temp);
      res=[...temp];
      }
      return res;
      };
      我的代码,这道题个人认为拼的是数学素养,随便来个8位长度的数组,然后天数N给个100天,打印出来后可以看到第1天和第15天、29天、43天,是一模一样的数组,由此可以优化为让N=N%14如果N恰好为0把N赋为14,一切就好做多了。做多了这种题好多可以用打印大法直接打印结果然后看结果有没有规律,有规律的基本是优化循环的次数,这类题我自己做的死去活来但好歹思路没太大问题,就是经常超时。但是动态规划,贪心算法还有许多涉及递归我是真的完全不会做思路都想不出来


      IP属地:广东3楼2018-12-26 09:54
      回复(9)