LeetCode 题解工作台
将整数按权重排序
我们将整数 x 的 权重 定义为按照下述规则将 x 变成 1 所需要的步数: 如果 x 是偶数,那么 x = x / 2 如果 x 是奇数,那么 x = 3 * x + 1 比方说,x=3 的权重为 7 。因为 3 需要 7 步变成 1 (3 --> 10 --> 5 --> 16 --> 8 --…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们先定义一个函数 ,表示将数字 变成 所需要的步数,也即是数字 的权重。 然后我们将区间 $[\textit{lo}, \textit{hi}]$ 内的所有数字按照权重升序排序,如果权重相同,按照数字自身的数值升序排序。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
我们将整数 x 的 权重 定义为按照下述规则将 x 变成 1 所需要的步数:
- 如果
x是偶数,那么x = x / 2 - 如果
x是奇数,那么x = 3 * x + 1
比方说,x=3 的权重为 7 。因为 3 需要 7 步变成 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)。
给你三个整数 lo, hi 和 k 。你的任务是将区间 [lo, hi] 之间的整数按照它们的权重 升序排序 ,如果大于等于 2 个整数有 相同 的权重,那么按照数字自身的数值 升序排序 。
请你返回区间 [lo, hi] 之间的整数按权重排序后的第 k 个数。
注意,题目保证对于任意整数 x (lo <= x <= hi) ,它变成 1 所需要的步数是一个 32 位有符号整数。
示例 1:
输入:lo = 12, hi = 15, k = 2 输出:13 解释:12 的权重为 9(12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) 13 的权重为 9 14 的权重为 17 15 的权重为 17 区间内的数按权重排序以后的结果为 [12,13,14,15] 。对于 k = 2 ,答案是第二个整数也就是 13 。 注意,12 和 13 有相同的权重,所以我们按照它们本身升序排序。14 和 15 同理。
示例 2:
输入:lo = 7, hi = 11, k = 4 输出:7 解释:区间内整数 [7, 8, 9, 10, 11] 对应的权重为 [16, 3, 19, 6, 14] 。 按权重排序后得到的结果为 [8, 10, 11, 7, 9] 。 排序后数组中第 4 个数字为 7 。
提示:
1 <= lo <= hi <= 10001 <= k <= hi - lo + 1
解题思路
方法一:自定义排序
我们先定义一个函数 ,表示将数字 变成 所需要的步数,也即是数字 的权重。
然后我们将区间 内的所有数字按照权重升序排序,如果权重相同,按照数字自身的数值升序排序。
最后返回排序后的第 个数字。
时间复杂度 ,空间复杂度 。其中 是区间 内的数字个数,而 是 的最大值,本题中 最大为 。
@cache
def f(x: int) -> int:
ans = 0
while x != 1:
if x % 2 == 0:
x //= 2
else:
x = 3 * x + 1
ans += 1
return ans
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
return sorted(range(lo, hi + 1), key=f)[k - 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) for sorting n = hi - lo + 1 integers, plus O(n * log m) for power computation using memoization (where m is the largest intermediate number). Space complexity is O(m) for the memoization table storing intermediate power values. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if memoization reduces repeated calculations of power values.
- question_mark
Expect clarification on sorting ties by ascending integer value.
- question_mark
Notice if the candidate uses a recursive DP vs iterative DP for power computation.
常见陷阱
外企场景- error
Failing to memoize powers leads to redundant recursion and timeouts.
- error
Sorting integers only by power without handling ties incorrectly orders results.
- error
Not handling k-1 indexing correctly when retrieving the k-th element.
进阶变体
外企场景- arrow_right_alt
Return all integers sorted by power instead of only the k-th element.
- arrow_right_alt
Compute power values using iterative DP rather than recursion with memoization.
- arrow_right_alt
Extend the range beyond 1000, requiring optimization for larger integers.