1 class Solution:
 2     def getKth(self, lo: int, hi: int, k: int) -> int:
 3         memo = dict()
 4         memo[1] = 0
 5         for i in range(1,hi+1):
 6             cur = i
 7             count = 0
 8             while cur != 1:
 9                 count += 1
10                 if cur % 2 == 0:#even
11                     cur = cur // 2
12                 else:
13                     cur = 3 * cur + 1
14                 if cur in memo:
15                     count += memo[cur]
16                     break
17             memo[i] = count
18         #print(memo)
19         temp = []
20         for key,val in memo.items():
21             if key >= lo and key <= hi:
22                 temp.append((key,val))
23         result = sorted(temp,key=lambda x:(x[1],x[0]))
24         return result[k-1][0]

算法思路:先使用备忘录机制(缓存),计算从1到hi的所有数字的steps。

然后按照题目要求,进行双条件排序。

posted on 2020-03-26 10:54  Sempron2800+  阅读(189)  评论(0编辑  收藏  举报