263.丑数
题目
编写一个程序判断给定的数是否为丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例 1:
输入: 6
输出: true
解释: 6 = 2 × 3
示例 2:
输入: 8
输出: true
解释: 8 = 2 × 2 × 2
示例 3:
输入: 14
输出: false
解释: 14 不是丑数,因为它包含了另外一个质因数 7。
说明:
1 是丑数。
输入不会超过 32 位有符号整数的范围: [−231, 231 − 1]。
【简单】
【分析】直接法和递归法都可以,直接法就是num依次整除2,3,4直到除不尽(即num%2!=0时)为止,最后判断若最后num==1,说明是丑数;否则不是。递归法和直接法其实类似。
class Solution:
def isUgly(self, num: int) -> bool:
if num==0:
return False
while num%2==0:
num/=2
while num%3==0:
num/=3
while num%5==0:
num/=5
if num==1:
return True
else:
return False
注意在python中运算符号/和//的区别
input: 3/1.1
Out: 2.727272727272727
input: 3//1.1
Out: 2.0 #返回的是floor(3/1.1)
264.丑数II
题目
编写一个程序,找出第 n 个丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
【中等】
【分析一】三指针方法
具体思路是通过前面得到的丑数乘以因数(2,3,5)来得到下一个丑数
f
n
f_n
fn:
- 前面的每个丑数 { f 1 , . . . , f n − 1 } \{f_1,...,f_{n-1}\} {f1,...,fn−1}都必须分别乘过因数2,3,5才行,所以用3个指针(index2,index3,index5)分别记录即将要乘这3个因数(2,3,5)的丑数的index;
- f n f_n fn则为 由上面3个指针中的丑数分别乘以相应因数得到的丑数中的最小丑数
class Solution:
def nthUglyNumber(self, n: int) -> int:
res=[1]
index2=0
index3=0
index5=0
while len(res)<n:
res2=res[index2]*2
res3=res[index3]*3
res5=res[index5]*5
tmp_res=min(res2,res3,res5)
if tmp_res==res2:
index2+=1
if tmp_res==res3:
index3+=1
if tmp_res==res5:
index5+=1
res.append(tmp_res)
return res[-1]
【分析二】还有一种更直接暴力的方法,从数字num=1开始,不断判断num是不是丑数,如果是就添加到表中,直到得到第n个丑数结果为止。
【注】本来想的是用2,3,5互相相乘的方法(从只有1个因数互相相乘开始,2个因数互相相乘,3个因数互相相乘,…,如此从上到下不断递归)得到丑数,最后sorted一下丑数输出第n个即可,但是,这种方法还是有问题,很有可能循环结束了得到了以为正确的结果,但是后面可能会存在相乘得到的丑数小于已有的结果,这就导致原有结果不准确(所以这么来看三指针方法还是比较合理的)。下面贴出这种方法的代码,供以后参考如何改正(注意下面这个代码是错的,目的是看看能有什么办法能修正)
class Solution:
def nthUglyNumber(self, n: int) -> int:
def nthUglyMultiply(last_lst,lst):
"""
"""
multiply_res=[]
for i in lst:
for j in last_lst:
tmp_res=i*j
if tmp_res not in multiply_res:
multiply_res.append(tmp_res)
return multiply_res
#n=12 #当n=12时,应该输出结果是16,所以程序输出错误
res=[1,2,3,5]
lst=[2,3,5]
if n<=3:
#print(res[n-1])
return res[n-1]
else:
last_lst=lst
while len(res)<=n:
last_lst=nthUglyMultiply(last_lst,lst)
res.extend(last_lst)
last_lst=nthUglyMultiply(last_lst,lst)
res.extend(last_lst)
res=sorted(res)
#print(res[n-1])
return res[n-1]