LeetCode 题解工作台
找到指定长度的回文数
给你一个整数数组 queries 和一个 正 整数 intLength ,请你返回一个数组 answer ,其中 answer[i] 是长度为 intLength 的 正回文数 中第 queries[i] 小的数字,如果不存在这样的回文数,则为 -1 。 回文数 指的是从前往后和从后往前读一模一样的…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 queries 和一个 正 整数 intLength ,请你返回一个数组 answer ,其中 answer[i] 是长度为 intLength 的 正回文数 中第 queries[i] 小的数字,如果不存在这样的回文数,则为 -1 。
回文数 指的是从前往后和从后往前读一模一样的数字。回文数不能有前导 0 。
示例 1:
输入:queries = [1,2,3,4,5,90], intLength = 3 输出:[101,111,121,131,141,999] 解释: 长度为 3 的最小回文数依次是: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... 第 90 个长度为 3 的回文数是 999 。
示例 2:
输入:queries = [2,4,6], intLength = 4 输出:[1111,1331,1551] 解释: 长度为 4 的前 6 个回文数是: 1001, 1111, 1221, 1331, 1441 和 1551 。
提示:
1 <= queries.length <= 5 * 1041 <= queries[i] <= 1091 <= intLength <= 15
解题思路
方法一
class Solution:
def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
l = (intLength + 1) >> 1
start, end = 10 ** (l - 1), 10**l - 1
ans = []
for q in queries:
v = start + q - 1
if v > end:
ans.append(-1)
continue
s = str(v)
s += s[::-1][intLength % 2 :]
ans.append(int(s))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate understands how to efficiently generate palindromes based on the length and query.
- question_mark
The candidate handles edge cases such as queries larger than the number of available palindromes.
- question_mark
The candidate can effectively use array and mathematical techniques to minimize computation.
常见陷阱
外企场景- error
Misunderstanding how to generate palindromes efficiently, leading to excessive computation or storage.
- error
Failing to handle edge cases where the query exceeds the number of possible palindromes.
- error
Incorrectly assuming palindromes can have leading zeros, which is not allowed in this problem.
进阶变体
外企场景- arrow_right_alt
What if the `intLength` were increased, making the palindromes larger?
- arrow_right_alt
How would you handle queries with very large values (e.g., `queries[i]` near 10^9)?
- arrow_right_alt
What if the problem allowed leading zeros in the palindromes?