当前位置:网站首页>leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]
leetcode: 1201. Ugly Number III [Dichotomy + Mathematics + Inclusion and Exclusion Principle]
2022-08-01 13:02:00 【Looking Back at the White Speed Dragon King】
分析
Ugly tree sequences cannot be repeated,So it is the union of three multiples
But it's not good,The principle of inclusion and exclusion unfolds
Expansion of the formula using the least common multiple becomes a monotonic non-decreasing onefx
fxThat is, less than or equal toxnumber of ugly trees
Divide to find the first makefx = n的x
It should be noted here that it is less thanl = mid + 1
大于等于r = mid
details
ac code
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
# 数学题 + 容斥原理
# 小于等于xThe number of ugly numbers is set to 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
# Divide to find the first makef(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
总结
The principle of inclusion and exclusion simplifies the problem Dichotomous solution
边栏推荐
- 【StoneDB Class】Introduction Lesson 2: Analysis of the Overall Architecture of StoneDB
- Qt获取文件夹下所有文件
- Aeraki Mesh Joins CNCF Cloud Native Panorama
- 收藏|机械工程师面试常问问题
- 动态库、静态库浅析
- 通讯录(静态版)(C语言)(VS)
- shell 中的 分发系统 expect脚本 (传递参数、自动同步文件、指定host和要传输的文件、(构建文件分发系统)(命令批量执行))
- 测试发文
- 如何利用DevExpress控件绘制流程图?看完这篇文章就懂了!
- PanGu-Coder:函数级的代码生成模型
猜你喜欢
CloudCompare & PCL ICP registration (point to face)
windows IDEA + PHP+xdebug 断点调试
找出相同属性值的对象 累加数量 汇总
这项工作事关中小学生生命安全!五部门作出联合部署
Beyond Compare 4 trial period expires
How to use DevExpress controls to draw flowcharts?After reading this article, you will understand!
SAP ABAP OData 服务如何支持创建(Create)操作试读版
让程序员早点下班的效率工具
蔚来又一新品牌披露:产品价格低于20万
数字孪生北京故宫,元宇宙推进旅游业进程
随机推荐
字体反爬之好租
formatdatetime函数 mysql(date sub函数)
Fault 007: The dexp derivative is inexplicably interrupted
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
数字孪生北京故宫,元宇宙推进旅游业进程
Visualization of lag correlation of two time series data in R language: use the ccf function of the forecast package to draw the cross-correlation function, and analyze the lag correlation according t
STM32 CAN过滤器配置详解
LeetCode_动态规划_中等_377.组合总和 Ⅳ
意大利普拉托华社将游行示威 盼解决安全问题
bat countdown code
收藏|机械工程师面试常问问题
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
Istio Meetup China:全栈服务网格 - Aeraki 助你在 Istio 服务网格中管理任何七层流量
ECCV22|只能11%的参数就能优于Swin,微软提出快速预训练蒸馏方法TinyViT
Aeraki Mesh 加入 CNCF 云原生全景图
MMF的初步介绍:一个规范化的视觉-语言多模态任务框架
脚本语言Lua的基础知识总结
什么是一致性哈希?可以应用在哪些场景?
8. SAP ABAP OData 服务如何支持创建(Create)操作
一文带你读懂云原生、微服务与高可用