LeetCode 题解工作台
判断一个数是否迷人
给你一个三位数整数 n 。 如果经过以下修改得到的数字 恰好 包含数字 1 到 9 各一次且不包含任何 0 ,那么我们称数字 n 是 迷人的 : 将 n 与数字 2 * n 和 3 * n 连接 。 如果 n 是迷人的,返回 true ,否则返回 false 。 连接 两个数字表示把它们首尾相接连在…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 哈希·数学
答案摘要
我们根据题目描述,将数字 与 $2 \times n$ 和 $3 \times n$ 连接,得到字符串 ,然后判断 是否包含数字 到 各一次且不包含任何 即可。 时间复杂度 $O(\log n)$,空间复杂度 $O(\log n)$。其中 为题目给定的整数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·数学 题型思路
题目描述
给你一个三位数整数 n 。
如果经过以下修改得到的数字 恰好 包含数字 1 到 9 各一次且不包含任何 0 ,那么我们称数字 n 是 迷人的 :
- 将
n与数字2 * n和3 * n连接 。
如果 n 是迷人的,返回 true,否则返回 false 。
连接 两个数字表示把它们首尾相接连在一起。比方说 121 和 371 连接得到 121371 。
示例 1:
输入:n = 192 输出:true 解释:我们将数字 n = 192 ,2 * n = 384 和 3 * n = 576 连接,得到 192384576 。这个数字包含 1 到 9 恰好各一次。
示例 2:
输入:n = 100 输出:false 解释:我们将数字 n = 100 ,2 * n = 200 和 3 * n = 300 连接,得到 100200300 。这个数字不符合上述条件。
提示:
100 <= n <= 999
解题思路
方法一:模拟
我们根据题目描述,将数字 与 和 连接,得到字符串 ,然后判断 是否包含数字 到 各一次且不包含任何 即可。
时间复杂度 ,空间复杂度 。其中 为题目给定的整数。
class Solution:
def isFascinating(self, n: int) -> bool:
s = str(n) + str(2 * n) + str(3 * n)
return "".join(sorted(s)) == "123456789"
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks the candidate’s understanding of string manipulation and number properties.
- question_mark
Looks for familiarity with hash tables for efficient validation of digits.
- question_mark
Evaluates problem-solving approach in terms of validation and optimization.
常见陷阱
外企场景- error
Not handling the case where the number contains zeroes.
- error
Misunderstanding the requirement for exactly one occurrence of each digit from 1 to 9.
- error
Not considering how to efficiently check the digits of the concatenated number.
进阶变体
外企场景- arrow_right_alt
Test with different ranges of n (e.g., edge cases with n = 100 or n = 999).
- arrow_right_alt
Try modifying the problem to work with numbers of different lengths.
- arrow_right_alt
Consider variations where the number could be non-three-digit and evaluate the change in constraints.