LeetCode 题解工作台

找到指定长度的回文数

给你一个整数数组 queries 和一个 正 整数 intLength ,请你返回一个数组 answer ,其中 answer[i] 是长度为 intLength 的 正回文数 中第 queries[i] 小的数字,如果不存在这样的回文数,则为 -1 。 回文数 指的是从前往后和从后往前读一模一样的…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 * 104
  • 1 <= queries[i] <= 109
  • 1 <= intLength <= 15
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

找到指定长度的回文数题解:数组·数学 | LeetCode #2217 中等