congr / world

2 stars 1 forks source link

LeetCode : 957. Prison Cells After N Days #468

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/prison-cells-after-n-days/

image image

congr commented 5 years ago
class Solution {
    public int[] prisonAfterNDays(int[] cells, int N) {
        // find day1 cells
        int[] day1 = new int[8]; 
        for (int i = 1; i < 7; i++)
            day1[i] = cells[i-1] == cells[i+1] ? 1 : 0;            

        // find cycle        
        int cycle = 0;
        while (N-- > 0) {
            int[] copy = new int[8];
            for (int i = 1; i < 7; i++) 
                copy[i] = cells[i-1] == cells[i+1] ? 1 : 0;            

            if (cycle > 1 && Arrays.equals(day1, copy)) N %= cycle; // !!!
            cells = copy.clone(); // !!!
            System.out.println(Arrays.toString(cells));

            cycle++;
        }

        return cells;
    }
}