当前位置:网站首页>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
总结
容斥原理简化问题 二分常规解决
边栏推荐
- 如何成功通过 CKA 考试?
- R语言拟合ARIMA模型:使用forecast包中的auto.arima函数自动搜索最佳参数组合、模型阶数(p,d,q)、设置seasonal参数指定在模型中是否包含季节信息
- 那些利用假期学习的职场人,后来都怎么样了?
- Do wildcard SSL certificates not support multiple domains?
- ddl and dml in sql (the difference between database table and view)
- 蔚来又一新品牌披露:产品价格低于20万
- 线上问题排查常用命令,总结太全了,建议收藏!!
- 一文带你彻底厘清 Kubernetes 中的证书工作机制
- How to get the address of WeChat video account (link address of WeChat public account)
- 并发编程10大坑,你踩过几个?
猜你喜欢
重磅消息 | Authing 实现与西门子低代码平台的集成
库函数的模拟实现(strlen)(strcpy)(strcat)(strcmp)(strstr)(memcpy)(memmove)(C语言)(VS)
Audio and Video Technology Development Weekly | 256
The CAN communication standard frame and extended frame is introduced
PanGu-Coder:函数级的代码生成模型
uniapp读取和写入文件
Feign 从注册到调用原理分析
MarkDown公式指导手册
2022 Go生态圈 rpc 框架 Benchmark
音视频技术开发周刊 | 256
随机推荐
小程序插件如何帮助开发者受益?
观察者模式
故障007:dexp导数莫名中断
Istio Meetup China:全栈服务网格 - Aeraki 助你在 Istio 服务网格中管理任何七层流量
Qt获取文件夹下所有文件
快速幂---学习笔记
线上问题排查常用命令,总结太全了,建议收藏!!
《MySQL核心知识》第6章:查询语句
易周金融分析 | 银行ATM机智能化改造提速;互联网贷款新规带来挑战
R language ggplot2 visualization: use ggpubr package ggscatter function visualization scatterplot, use xscale wasn't entirely specified X axis measurement adjustment function, set the X coordinate for
Deep understanding of Istio - advanced practice of cloud native service mesh
[Open class preview]: Research and application of super-resolution technology in the field of video quality enhancement
R语言拟合ARIMA模型:使用forecast包中的auto.arima函数自动搜索最佳参数组合、模型阶数(p,d,q)、设置seasonal参数指定在模型中是否包含季节信息
一文带你彻底厘清 Isito 中的证书工作机制
Aeraki Mesh became CNCF sandbox project
字体反爬之好租
How to integrate 3rd party service center registration into Istio?
Alibaba Cloud Official Redis Development Specification
Envoy source code flow chart
R语言ggplot2可视化:使用ggpubr包的ggscatter函数可视化散点图、使用xscale函数指定X轴坐标轴度量调整方式、设置x轴坐标为scientific使用科学计数法显示坐标值