• 【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
  • 相关阅读:
    MSSQL查询表占用空间
    JS字典
    匹配是否指定主域名
    站点文件删除不了提示权限不足
    事件委托发布-订阅
    微信中打开第三方应用
    以Spring Bean配置文件为例解释 xmlns,xmlns:xsi,xsi:schemaLocation
    Hdfs的读出机制
    Hdfs的写入机制
    spring常用注解的作用
  • 原文地址:https://www.cnblogs.com/seyjs/p/10135651.html
Copyright © 2020-2023  润新知