当前位置:网站首页>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
边栏推荐
- Software designer test center summary (interior designer personal summary)
- Grafana 9.0 released, Prometheus and Loki query builders, new navigation, heatmap panels and more!
- SCHEMA solves the puzzle
- 关于Request复用的那点破事儿。研究明白了,给你汇报一下。
- 数字证书原理
- 音视频技术开发周刊 | 256
- Complete Raiders of JS Data Type Conversion
- How to integrate 3rd party service center registration into Istio?
- 初级必备:单例模式的7个问题
- markdown常用数学符号cov(markdown求和符号)
猜你喜欢
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement
STM32 CAN过滤器配置详解
脚本语言Lua的基础知识总结
数据湖 delta lake和spark版本对应关系
观察者模式
关于Request复用的那点破事儿。研究明白了,给你汇报一下。
bpmn-process-designer基础上进行自定义样式(工具、元素、菜单)
批量替换Word中的表格为图片并保存
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
如何使用 Authing 单点登录,集成 Discourse 论坛?
随机推荐
The four methods of judging JS data type
8. SAP ABAP OData 服务如何支持创建(Create)操作
bat countdown code
意大利普拉托华社将游行示威 盼解决安全问题
SAP ABAP OData 服务如何支持创建(Create)操作试读版
CloudCompare & PCL ICP registration (point to face)
bat倒计时代码
SQL function SQRT
快速幂---学习笔记
LeetCode_动态规划_中等_377.组合总和 Ⅳ
Simulation implementation of new of Js handwritten function
SQL function SQUARE
阿里云官方 Redis 开发规范
动态库、静态库浅析
关于Request复用的那点破事儿。研究明白了,给你汇报一下。
Detailed explanation of table join
[Unity3D Plugin] AVPro Video Plugin Share "Video Player Plugin"
故障007:dexp导数莫名中断
CAN通信的数据帧和远程帧
[Community Star Selection] Issue 24 August Update Plan | Keep writing, refuse to lie down!More original incentive packages, as well as Huawei WATCH FIT watches!