前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 957. Prison Cells After N Days

Leetcode 957. Prison Cells After N Days

作者头像
Tyan
发布2021-09-06 15:38:48
4360
发布2021-09-06 15:38:48
举报
文章被收录于专栏:SnailTyanSnailTyan

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

Prison Cells After N Days
Prison Cells After N Days

2. Solution

**解析:**Version 1,根据变换规则可知,第一位和最后一位总是0,因此只有中间6位数在变,最大可能的变换周期为2^6。因此只要记录变换周期,因此周期中的所有状态就可得出变换结果,使用字典stat来判断每次变换是否与之前的重复,列表state记录状态变化,当出现重复状态时,计算变换的周期peroid,以及一个周期的状态变化,如果没出现周期,则直接返回变换后的结果,如果出现了,则返回计算后的状态。

  • Version 1
代码语言:javascript
复制
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/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档