当前位置:网站首页>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
总结
容斥原理简化问题 二分常规解决
边栏推荐
- Programmer's self-cultivation
- formatdatetime function mysql (date sub function)
- 程序员如何优雅地解决线上问题?
- 数据湖 delta lake和spark版本对应关系
- markdown常用数学符号cov(markdown求和符号)
- 力扣160题,相交链表
- R语言ggplot2可视化:使用ggpubr包的ggdensity函数可视化密度图、使用stat_central_tendency函数在密度中添加均值竖线并自定义线条类型
- win10系统重装,无法登录进行同步的情况下chrome数据恢复
- 【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用
- 那些利用假期学习的职场人,后来都怎么样了?
猜你喜欢
随机推荐
R语言检验时间序列的平稳性:使用tseries包的adf.test函数实现增强的Dickey-Fuller(ADF)检验、检验时序数据是否具有均值回归特性(平稳性)、具有均值回归特性的案例
[Nodejs] fs module of node
Envoy 源码流程图
[5 days countdown] to explore the secret behind the great quality promotion, gift waiting for you to take of $one thousand
R语言拟合ARIMA模型:使用forecast包中的auto.arima函数自动搜索最佳参数组合、模型阶数(p,d,q)、设置seasonal参数指定在模型中是否包含季节信息
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
How to Integrate Your Service Registry with Istio?
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
线上问题排查常用命令,总结太全了,建议收藏!!
计算器:中缀表达式转后缀表达式
[Cloud Enjoying Freshness] Community Weekly Vol.73- DTSE Tech Talk: 1 hour in-depth interpretation of SaaS application system design
Meshlab&Open3D SOR滤波
uniapp读取和写入文件
关于亚马逊测评,你了解多少?
SQL函数 SQRT
数据湖 delta lake和spark版本对应关系
如何将第三方服务中心注册集成到 Istio ?
英特尔全方位打造算力基础,助推“算”赋百业
找出相同属性值的对象 累加数量 汇总
深入解析volatile关键字