当前位置:网站首页>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
总结
容斥原理简化问题 二分常规解决
边栏推荐
- 易周金融分析 | 银行ATM机智能化改造提速;互联网贷款新规带来挑战
- pandas connects to the oracle database and pulls the data in the table into the dataframe, filters all the data from the current time (sysdate) to one hour ago (filters the range data of one hour)
- The four methods of judging JS data type
- Complete Raiders of JS Data Type Conversion
- Software designer test center summary (interior designer personal summary)
- SQL函数 %SQLSTRING
- 将同级数据处理成树形数据
- R语言拟合ARIMA模型:使用forecast包中的auto.arima函数自动搜索最佳参数组合、模型阶数(p,d,q)、设置seasonal参数指定在模型中是否包含季节信息
- MVVM响应式
- 2022 Go ecosystem rpc framework Benchmark
猜你喜欢
随机推荐
How to Integrate Your Service Registry with Istio?
windows IDEA + PHP+xdebug 断点调试
R语言检验时间序列的平稳性:使用tseries包的adf.test函数实现增强的Dickey-Fuller(ADF)检验、检验时序数据是否具有均值回归特性(平稳性)、具有均值回归特性的案例
线上问题排查常用命令,总结太全了,建议收藏!!
CloudCompare & PCL ICP registration (point to face)
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
[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!
腾讯云原生:Areaki Mesh 在 2022 冬奥会视频直播应用中的服务网格实践
【Unity3D插件】AVPro Video插件分享《视频播放插件》
【面试高频题】难度 1.5/5,二分经典运用题
数字证书原理
一文带你彻底厘清 Kubernetes 中的证书工作机制
AI目标分割能力,无需绿幕即可实现快速视频抠图
ddl and dml in sql (the difference between database table and view)
Meshlab&Open3D SOR滤波
markdown常用数学符号cov(markdown求和符号)
为什么最大值加一等于最小值
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
Dapr 与 NestJs ,实战编写一个 Pub & Sub 装饰器
将同级数据处理成树形数据