-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# [1387. 将整数按权重排序](https://leetcode.cn/problems/sort-integers-by-the-power-value/description/) | ||
|
||
> **日期**:2024-12-22 | ||
> **所用时间**:5min | ||
## 1. 记忆化搜索 | ||
|
||
使用记忆化搜索保存每个数字 $x$ 变成 $1$ 所需要的步骤数,减少状态的重复计算。 | ||
|
||
将 $[lo, hi]$ 之间的所有数字的步骤数都计算出来,然后按照题意进行排序,之后返回排序后的第 $k$ 个数即为答案。 | ||
|
||
- 时间复杂度: $O(nlogn)$ | ||
- 空间复杂度: $O(n)$ | ||
|
||
**Python3** | ||
|
||
```python | ||
class Solution: | ||
def getKth(self, lo: int, hi: int, k: int) -> int: | ||
@cache | ||
def get(x: int) -> int: | ||
if x == 1: | ||
return 0 | ||
if x % 2: | ||
return get(3 * x + 1) + 1 | ||
return get(x / 2) + 1 | ||
|
||
nums = [(get(x), x) for x in range(lo, hi + 1)] | ||
nums.sort() | ||
return nums[k - 1][1] | ||
``` |