Skip to content

Commit

Permalink
2024-12-22打卡
Browse files Browse the repository at this point in the history
  • Loading branch information
NoyeArk committed Dec 22, 2024
1 parent a7dfcbe commit 06ed6ca
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions leetcode/4-每日一题/1387. 将整数按权重排序.md
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]
```

0 comments on commit 06ed6ca

Please sign in to comment.