当前位置:网站首页>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
边栏推荐
- 蔚来又一新品牌披露:产品价格低于20万
- SQL函数 STR
- Istio Meetup China:全栈服务网格 - Aeraki 助你在 Istio 服务网格中管理任何七层流量
- 2022 Go生态圈 rpc 框架 Benchmark
- Find objects with the same property value Cumulative number Summarize
- AI目标分割能力,无需绿幕即可实现快速视频抠图
- 达梦更换正式授权dm.key
- 10年稳定性保障经验总结,故障复盘要回答哪三大关键问题?|TakinTalks大咖分享
- 快速幂---学习笔记
- How much do you know about Amazon reviews?
猜你喜欢
随机推荐
关于Request复用的那点破事儿。研究明白了,给你汇报一下。
Qt get all files in a folder
并发编程10大坑,你踩过几个?
This article will take you to thoroughly clarify the working mechanism of certificates in Isito
态路小课堂丨浅谈优质光模块需要具备的条件!
SQL函数 %SQLSTRING
SQL函数 STR
Meshlab & Open3D SOR filtering
Qt获取文件夹下所有文件
一文带你读懂云原生、微服务与高可用
软件设计师考点汇总(室内设计师个人总结)
为什么最大值加一等于最小值
Deep understanding of Istio - advanced practice of cloud native service mesh
脚本语言Lua的基础知识总结
动态库、静态库浅析
Dapr 与 NestJs ,实战编写一个 Pub & Sub 装饰器
【面试高频题】难度 1.5/5,二分经典运用题
字体反爬之好租
Js手写函数之new的模拟实现
程序员如何优雅地解决线上问题?









