当前位置:网站首页>leetcode:1201. 丑数 III【二分 + 数学 + 容斥原理】
leetcode:1201. 丑数 III【二分 + 数学 + 容斥原理】
2022-08-01 12:46:00 【白速龙王的回眸】

分析
丑树序列不能重复,所以是三个倍数之并
但并不好求,容斥原理展开
利用最小公倍数展开公式成为一个单调不减的fx
fx即为小于等于x的丑树的个数
二分找到第一个使得fx = n的x
这里需要注意一下是小于的话l = mid + 1
大于等于r = mid
细节一下
ac code
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
# 数学题 + 容斥原理
# 小于等于x的丑数个数设成f(x)
# 两个数的最小公倍数
def lcm(a, b):
return (a * b) // gcd(a, b)
# 三个数的最小公倍数
def lcm3(a, b, c):
return lcm(lcm(a, b), c)
# 容斥原理:|A or B or C| = |A| + |B| + |C| - |A and B| - |B and C| - |C and A| + |A and B and C|
def f(x):
f1 = x // a + x // b + x // c
f2 = x // lcm(a, b) + x // lcm(b, c) + x // lcm(c, a)
f3 = x // lcm3(a, b, c)
return f1 - f2 + f3
# 二分找到第一个使得f(x) = n的x
# 因为fx单调不减
l, r = 1, 2 * 10 ** 9
while l < r:
mid = (l + r) // 2
if f(mid) < n:
l = mid + 1
else:
r = mid
return l
总结
容斥原理简化问题 二分常规解决
边栏推荐
- How to Integrate Your Service Registry with Istio?
- 阿里云官方 Redis 开发规范
- 那些利用假期学习的职场人,后来都怎么样了?
- Beyond Compare 4 trial period expires
- 小程序插件如何帮助开发者受益?
- How to get the address of WeChat video account (link address of WeChat public account)
- Grafana9.0发布,Prometheus和Loki查询生成器、全新导航、热图面板等新功能!
- 这项工作事关中小学生生命安全!五部门作出联合部署
- 如何将第三方服务中心注册集成到 Istio ?
- What is MNIST (what does plist mean)
猜你喜欢

windows IDEA + PHP+xdebug 断点调试

安装apex报错

【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
![[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement](/img/fc/cd859efa69fa7b45f173de74c04858.png)
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement

达梦更换正式授权dm.key

如何使用 Authing 单点登录,集成 Discourse 论坛?

Programmer's self-cultivation

【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用

Windows 安装PostgreSQL

观察者模式
随机推荐
Feign 从注册到调用原理分析
SQL函数 SQRT
大中型网站列表页翻页过多怎么优化?
STM32 CAN filter configuration details
R语言ggplot2可视化:使用ggpubr包的geom_exec函数执行geom_*函数(没有任何参数需要放置在aes中)
数字孪生北京故宫,元宇宙推进旅游业进程
AI目标分割能力,无需绿幕即可实现快速视频抠图
Envoy source code flow chart
Data frame and remote frame of CAN communication
软件设计师考点汇总(室内设计师个人总结)
R语言两个时间序列数据的滞后相关性可视化:使用forecast包的ccf函数绘制交叉相关函数,根据可视化结果分析滞后相关性
R language fitting ARIMA model: use the auto.arima function in the forecast package to automatically search for the best parameter combination, model order (p, d, q), set the seasonal parameter to spe
Aeraki Mesh became CNCF sandbox project
Alibaba Cloud Official Redis Development Specification
意大利普拉托华社将游行示威 盼解决安全问题
MVVM响应式
How do programmers solve online problems gracefully?
通讯录(静态版)(C语言)(VS)
Qt get all files in a folder
Beyond Compare 4 试用期到期