Leetcode 957. Prison Cells After N Days

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡(jiǎn)書

1. Description

Prison Cells After N Days

2. Solution

解析:Version 1,根據(jù)變換規(guī)則可知,第一位和最后一位總是0,因此只有中間6位數(shù)在變,最大可能的變換周期為2^6。因此只要記錄變換周期,因此周期中的所有狀態(tài)就可得出變換結(jié)果,使用字典stat來判斷每次變換是否與之前的重復(fù),列表state記錄狀態(tài)變化,當(dāng)出現(xiàn)重復(fù)狀態(tài)時(shí),計(jì)算變換的周期peroid,以及一個(gè)周期的狀態(tài)變化,如果沒出現(xiàn)周期,則直接返回變換后的結(jié)果,如果出現(xiàn)了,則返回計(jì)算后的狀態(tài)。

  • Version 1
class Solution:
    def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
        stat = {}
        state = []
        temp = ''.join(list(map(str, cells)))
        stat[temp] = 0
        count = 0
        pre = cells[:]
        state.append(pre)
        for i in range(n):
            count += 1
            cells[0] = 0
            cells[7] = 0
            for j in range(1, 7):
                if (pre[j-1] == 1 and pre[j+1] == 1) or (pre[j-1] == 0 and pre[j+1] == 0):
                    cells[j] = 1
                else:
                    cells[j] = 0
            temp = ''.join(list(map(str, cells)))
            if temp not in stat:
                stat[temp] = count
                pre = cells[:]
                state.append(pre)
            else:
                peroid = count - stat[temp]
                state = state[stat[temp]:]
                break
        if count == n:
            return cells
        return state[(n - count) % peroid]

Reference

  1. https://leetcode.com/problems/prison-cells-after-n-days/
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容