1. 程式人生 > >Java/957. Prison Cells After N Days N天后的牢房

Java/957. Prison Cells After N Days N天后的牢房

題目


 

 

 

 

題目不難,很容易找到思路,比較坑的是找迴圈節。(一個小技巧,給的Example1中有七個資料,從這個數字開始到雙倍、三倍)一般題目不會無端給這麼多測試資料的

 

程式碼部分一(12ms 85.61%)

class Solution {
    public int[] prisonAfterNDays(int[] cells, int N) {
        if(N <= 0) return cells;
        if(N%14 == 0){
            N = 14;
        }else {
            N = N%14;
        }
        while(N > 0){
            int[] res = new int[8];
            res[0] = 0;
            res[7] = 0;
            for(int i = 1; i < 7; i++){
                 res[i] = (cells[i-1] ^ cells[i+1]) ^ 1;
            }
            cells = res;
            N--;
        }
        
        
        return cells;
    }
}

 

程式碼部分二(11ms 100%)

class Solution {
    public int[] prisonAfterNDays(int[] cells, int N) {
        if(N = 0) return cells;
        if(N%14 == 0){
            N = 14;
        }else {
            N = N%14;
        }
        while(N  0){
            int[] res = new int[8];
            res[0] = 0;
            res[7] = 0;
            for(int i = 1; i  7; i++){
                if(cells[i-1] == cells[i+1]) res[i] = 1;
                else res[i] = 0;
            }
            cells = res;
            N--;
        }
        
        
        return cells;
    }
}