zoukankan      html  css  js  c++  java
  • 0957. Prison Cells After N Days (M)

    Prison Cells After N Days (M)

    题目

    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

    题意

    给定一个一维数组cells,进行N次循环,每次循环中如果cells[i]邻接的两个元素都为1或都为0,则cells[i]变为1,否则cells[i]变为0。首元素和末元素只会变为0。求N次循环后数组的状态。

    思路

    0289. Game of Life (M) 有点类似,每次状态的变更都是同时发生的,不能用前一个变化后的值去影响后一个将要改变的值。每次循环可以直接复制一个数组进行操作。同时,打表可以发现数组的状态是有规律的,以14作为一个周期,因此N等效于(N-1)%14+1。


    代码实现

    Java

    class Solution {
        public int[] prisonAfterNDays(int[] cells, int N) {
            N = (N - 1) % 14 + 1;
            for (int i = 1; i <= N; i++) {
                int[] aux = Arrays.copyOf(cells, 8);
                for (int j = 1; j < 7; j++) {
                    cells[j] = aux[j - 1] == aux[j + 1] ? 1 : 0;
                }
                cells[0] = cells[7] = 0;
            }
            return cells;
        }
    }
    
  • 相关阅读:
    ES6 新属性 Symbol
    box-shadow 属性详解
    在vue 中 使用 tinymce编辑器
    var let const 结合作用域 的探讨
    防抖和节流在vue中的应用
    分享几个按钮样式
    队列学习
    栈的学习
    Object—常用的遍历
    从零认识Java Package
  • 原文地址:https://www.cnblogs.com/mapoos/p/13233510.html
Copyright © 2011-2022 走看看