zoukankan      html  css  js  c++  java
  • 【leetcode】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.)

    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 1:

    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]
    
    

    Example 2:

    Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
    Output: [0,0,1,1,1,1,1,0]
    

    Note:

    1. cells.length == 8
    2. cells[i] is in {0, 1}
    3. 1 <= N <= 10^9

    解题思路:当我看到第二个用例中 N = 1000000000 后,直觉告诉我变换结果中应该存在周期性的循环。所以我就测试了前100天结果,发现这个周期是14天。这也是是一种取巧的方法了。

    代码如下:

    class Solution(object):
        def prisonAfterNDays(self, cells, N):
            """
            :type cells: List[int]
            :type N: int
            :rtype: List[int]
            """
            if N != 0:
                N = N % 14 if N % 14 != 0 else 14
            while N > 0:
                tl = [0]
                for i in range(1,len(cells)-1):
                    if cells[i-1] == cells[i+1]:
                        tl.append(1)
                    else:
                        tl.append(0)
                tl.append(0)
                cells = tl[:]
                N -= 1
            return cells
  • 相关阅读:
    TypeError: can't compare offset-naive and offset-aware datetimes bugfix
    pg_restore数据库恢复指令
    第四十期百度技术沙龙笔记整理
    JS事件模型小结
    matlab Newton method
    Markdown 语法的简要规则
    iOS社交分享Twitter、Facebook、拷贝到剪切板、LINE、及邮件
    Linux系统调用过程分析
    iOS自己定义返回button(不影响返回手势)
    MAVEN项目模块化
  • 原文地址:https://www.cnblogs.com/seyjs/p/10135651.html
Copyright © 2011-2022 走看看