描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
首先从丑数的定义我们知道,一个丑数的因子只有2,3,5,那么丑数。
得出来的丑数序列依次为[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15 ...]
讨论组题解:
①
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
if index < 1:
return 0
res = [1]
t2 = t3 = t5 = 0
nextIdx = 1
while nextIdx < index:
minNum = min(res[t2] * 2, res[t3] * 3, res[t5] * 5)
res.append(minNum)
while res[t2] * 2 <= minNum:
t2 += 1
while res[t3] * 3 <= minNum:
t3 += 1
while res[t5] * 5 <= minNum:
t5 += 1
nextIdx += 1
return res[nextIdx - 1]
②python三行解法:
def GetUglyNumber_Solution(self, index):
res=[2**i*3**j*5**k for i in range(30) for j in range(20) for k in range(15)]
res.sort()
return res[index-1] if index else 0
③python两行解法:
def GetUglyNumber_Solution(self, index):
res=[2**i*3**j*5**k for i in range(30) for j in range(20) for k in range(15)]
return sorted(res)[index-1] if index else 0
④python一行解法:
return sorted([2**i*3**j*5**k for i in range(30) for j in range(20) for k in range(15)])[index-1] if index else 0
该博客介绍了如何使用Python高效地求解丑数序列,包括四种不同的实现方法:①迭代法,通过维护三个指针跟踪2、3、5的乘积;②三行解法,通过遍历2、3、5的幂组合;③两行解法,同上,但更紧凑;④一行解法,将上述过程进一步压缩为单行代码。这些方法都用于找到第N个丑数。
235

被折叠的 条评论
为什么被折叠?



