LeetCode 题解工作台
第 N 个神奇数字
一个正整数如果能被 a 或 b 整除,那么它是神奇的。 给定三个整数 n , a , b ,返回第 n 个神奇的数字。因为答案可能很大,所以返回答案 对 10 9 + 7 取模 后的值。 示例 1: 输入: n = 1, a = 2, b = 3 输出: 2 示例 2: 输入: n = 4, a =…
2
题型
4
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
根据题目描述,神奇数字是能被 或 整除的正整数。 而我们知道,对于任意正整数 ,在 范围内,能被 整除的数有 $\lfloor \frac{x}{a} \rfloor$ 个,能被 整除的数有 $\lfloor \frac{x}{b} \rfloor$ 个,能被 和 同时整除的数有 $\lfloor \frac{x}{c} \rfloor$ 个,其中 是 和 的最小公倍数。最小公…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
一个正整数如果能被 a 或 b 整除,那么它是神奇的。
给定三个整数 n , a , b ,返回第 n 个神奇的数字。因为答案可能很大,所以返回答案 对 109 + 7 取模 后的值。
示例 1:
输入:n = 1, a = 2, b = 3 输出:2
示例 2:
输入:n = 4, a = 2, b = 3 输出:6
提示:
1 <= n <= 1092 <= a, b <= 4 * 104
解题思路
方法一:数学 + 二分查找
根据题目描述,神奇数字是能被 或 整除的正整数。
而我们知道,对于任意正整数 ,在 范围内,能被 整除的数有 个,能被 整除的数有 个,能被 和 同时整除的数有 个,其中 是 和 的最小公倍数。最小公倍数的计算公式为 。
因此,对于任意正整数 ,在 范围内,神奇数字的个数为:
为什么要减去 呢?可以这样理解,在 范围内,能被 和 同时整除的数,它们既能被 整除,也能被 整除,因此它们被计算了两次,需要减去一次。
题目要我们找到第 个神奇数字,也即是说,要找到一个最小的正整数 ,使得以下式子成立:
随着 的增大,神奇数字的个数也会增大,因此我们可以使用二分查找的方法,找到最小的正整数 ,使得上述式子成立。
注意答案的取模操作。
时间复杂度 ,空间复杂度 。其中 是二分查找的上界,本题可以取 。
class Solution:
def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
mod = 10**9 + 7
c = lcm(a, b)
r = (a + b) * n
return bisect_left(range(r), x=n, key=lambda x: x // a + x // b - x // c) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of binary search and inclusion-exclusion principles.
- question_mark
The candidate can efficiently handle large inputs and avoid brute force solutions.
- question_mark
The candidate successfully uses modulo arithmetic to prevent overflow in large numbers.
常见陷阱
外企场景- error
Forgetting to handle large values with modulo operation, causing overflow.
- error
Misapplying the inclusion-exclusion principle when counting multiples of a and b.
- error
Using a brute force solution that will not scale well with the input size.
进阶变体
外企场景- arrow_right_alt
What if n is extremely large, and we need to handle the computation efficiently?
- arrow_right_alt
What if a and b are very large numbers? How does this affect the binary search range?
- arrow_right_alt
Can this problem be solved with a greedy approach instead of binary search?