LeetCode 957. * Cells After N Days

原题链接在这里:https://leetcode.com/problems/*-cells-after-n-days/

题目:

There are 8 * 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 * 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 * in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.

Given the initial state of the *, return the state of the * 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 * 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

题解:

Brute idea is to do it like having a temp array and update temp, then cells = temp.

But the state repeated every 2 * (cells.length - 1) times. 

Thus use k = (N - 1) %  (2 * (cells.length - 1)) + 1.

Why not use k = n % (2 * (cells.length - 1)). Because when N = 2 * (cells.length - 1). We still need to perform action, the result is not equal to N = 0.

Time Complexity: O(n ^ 2). n = cells.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int[] *AfterNDays(int[] cells, int N) {
 3         if(cells == null || cells.length == 0 || N <= 0){
 4             return cells;
 5         }
 6         
 7         int n = cells.length;
 8         for(int k = (N - 1) % (2 * (n - 1)) + 1; k > 0; k--){
 9             int [] temp = new int[n];
10             for(int i = 1; i < n - 1; i++){
11                 if(cells[i - 1] == cells[i + 1]){
12                     temp[i] = 1;
13                 }
14             }
15             
16             cells = temp;
17         }
18         
19         return cells;
20     }
21 }

 

上一篇:dts解析【转】


下一篇:从零开始写设备树DTS【转】