当前位置:网站首页>Leetcode 1387.将整数按权重排序(Sort Integers by The Power Value)
Leetcode 1387.将整数按权重排序(Sort Integers by The Power Value)
2022-04-21 06:35:00 【就叫昵称吧】
Leetcode 1387.将整数按权重排序
1 题目描述(Leetcode题目链接)
我们将整数 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 位有符号整数。
输入: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 题解
直接sorted
class Solution:
def getWeight(self, x):
i = 0
while x != 1:
if x & 1:
x = 3*x + 1
else:
x >>= 1
i += 1
return i
def getKth(self, lo: int, hi: int, k: int) -> int:
arr = sorted(range(lo, hi + 1), key = lambda x:(self.getWeight(x), x))
return arr[k - 1]
版权声明
本文为[就叫昵称吧]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_39378221/article/details/109601607
边栏推荐
- MySQL common table structure
- Sort method (2) = > insert sort
- Jichuang north, chipone, icn6211, icn6202, Mipi to RGB, Mipi to LVDS, maximum resolution 1080p, Mipi DSI conversion, Mipi conversion,
- 2022-1-3至2022-1-16 访问者模式
- Financial information security training - 22 / 4 / 18
- BGP 鄰居
- BGP neighbor
- About IMAP tools module to achieve mail movement
- Detailed explanation of the whole evolution process and architecture design of large websites
- 2020-12-25
猜你喜欢

Audio power amplifier, ns4165b single channel 5.3w class AB \ D power amplifier, mainly replacing cs8571, cs8871 and cs5218 of Zhipu core and haa2018 of hailichuang

NP and OSPF monitoring and commissioning

三层交换机与路由器对接上网

利用安全漏洞检测工具Metasploit对靶机Metasploitable2的Telnet登录提权

状态模式(4.4-4.10)

OSPF multi area

(2022.1.31-2022.2.14)模板模式解析

【WPF】UpdateSourceTrigger

【WPF】自定义控件

NP、NSSA区域
随机推荐
Switching technology
Concepts related to computer vulnerability security POC, exp, vul, CVE, 0day
NP、OSPF基本配置
BGP 认证功能
状态模式(4.4-4.10)
NP、OSPF路由聚合
链表(C语言)
【WPF】自定义控件
【WPF】UpdateSourceTrigger
NP, OSPF stub area
IGMP_华为
NP, OSPF link state database
OSPF multi area
Leetcode 1561.你可以获得的最大硬币数目(Maximum Number of Coins You Can Get)
【WPF】利用RadioButton制作导航条
NP, NSSA area
2022-1-17至2022-1-30 迭代器模式
Defining “Disinformation“(定义“虚假信息”)
On balanced binary tree
【网络协议】为什么要学习网络协议