当前位置:网站首页>[英雄星球七月集训LeetCode解题日报] 第16日 队列
[英雄星球七月集训LeetCode解题日报] 第16日 队列
2022-07-16 14:43:00 【七水shuliang】
日报
- 今天只有一题
题目
一、2327. 知道秘密的人数
链接: 2327. 知道秘密的人数
1. 题目描述

2. 思路分析
这题其实是斐波那契兔子的变种。
周赛时用的*O(n2)*的线性DP,思考起来比较复杂,具体可以参加我之前的[LeetCode周赛复盘] 第 300 场周赛20220703。
- 今天写一下*O(n)*的做法。
- 定义f[i]为第i天新知道秘密的人的人数,那么转移可以通过刷表法转移。
- 通常我们做dp都是针对dp[i],看它能从哪个子状态(如dp[i-1]…dp[j],j<i)转移而来,叫填表法;这里刷表法指的是,处理dp[i]时,看dp[i]能对哪个dp[k]产生贡献,去更新dp[k]的值。
- 刷表法的题目之前刚好做过一道: 871. 最低加油次数,当然这题可以贪心+优先队列做。
- 返回这题,刷表其实非常简单了,对于第i天新知道秘密的人数,他们会在第i+delay天开始产生新的人,一直到i+forget天结束(这里注意不要越界)。
- 最后一段会产生一个如果这帮人产生新人的时间越界了,且他们没遗忘,那他们要累计到答案里,用cnt_b储存(cnt_b代表知道秘密但不能分享的人);
- 这个算法依然是*O(n2)*的,我们发现内层循环有一个区间加的运算,因此可以差分数组优化。

3. 代码实现
MOD = 10**9+7
class Solution:
def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:
diff = [0] * n # 用差分数组储存 第i天知道秘密且能分享的人
cnt_b = 0
diff[0] = 1
diff[1] = -1
f = 0
for i,d in enumerate(diff):
f = (f+d)%MOD
if i+delay>=n:
cnt_b += f
else:
diff[i+delay] += f
if i+forget<n:
diff[i+forget] -= f
return (f + cnt_b)%MOD
参考链接
边栏推荐
- 耐克,体育运动龙头在消费复苏趋势中的“红与黑”
- 服装ERP怎么选?选型时一定要问这些问题
- Flask response
- mysql的连接查询
- 【C语言刷LeetCode】1744. 你能在你最喜欢的那天吃到你最喜欢的糖果吗(M)
- Leetcode refers to the average value of offer II 041 sliding window [sliding window] the way of leetcode in heroding
- golang中的读写锁原理
- 844. Compare strings with backspace
- The principle and implementation of ring queue
- Upupwank teak peel installation SSL certificate Guide
猜你喜欢

Seventh note: machine level code representation of programs

深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!

1.创建Prism项目

论文翻译解读:learning logic rules for reasoning on knowledge graphs【RNNLogic】

图扑软件构建源网荷储用体系 打造循环经济2.0版本

impala高级设置之BROADCAST_BYTES_LIMIT

ctf-pikachu-sql

The principle and implementation of ring queue

复盘:BN和Dropout共同使用时会出现的问题

三面头条+四面阿里+五面腾讯拿offer分享面经总结,最终入职阿里
随机推荐
《遥远的救世主》遵守客观规律(六)——文化属性
一文详解图像中的无监督学习
ctf-pikachu-RCE
Halcon and C # detect surface defects - ROI interaction (II) (functions such as synchronous scaling and clipping with pictures)
《遥远的救世主》遵守客观规律(五)——文化属性
A game research and development company in Shenzhen installed monitoring for each station. Netizen: it's comparable to imprisonment!
MySQL 变量、流程控制与游标练习
Sword finger offer 52 The first common node of two linked lists
【Ucos-III源码分析】——软件定时器
About STM32 driving LCD display screen, the solution to the problem that the white screen and disordered code need to be powered on and reset to return to normal after the program is downloaded
Huawei equipment RF resource management command
Impala advanced settings of broadcast_ BYTES_ LIMIT
TCP拥塞控制详解 | 6. 主动队列管理
STM32——定时器中断实验
Preparing transaction:done Verifying transaction:failed RemoveError:‘requests‘ is a dependency of **
电流镜自动布局 布局对称性: 量化和应用以消除非线性过程梯度
【毕业设计】基于情感分析的网络舆情热点分析系统
【Ucos-III源码分析】——事件标志组
Bean的生命周期详解
[graduation project] network public opinion hotspot analysis system based on Emotional Analysis