@Author：Runsen

@Date:2020/9/28

# 什么是丑数

Talk is cheap ,show me my code !

# Leetcode 263：判断给定的数是否为丑数

# 递归的做法
class Solution:
def isUgly(self, num: int) -> bool:
if num <= 0:
return False
elif num <=6 :
return True
if num % 2 == 0:
return self.isUgly(num / 2)
if num % 3 == 0:
return self.isUgly(num / 3)
if num % 5 == 0:
return self.isUgly(num / 5)
return False

# while循环暴力破解
class Solution:
def isUgly(self, num: int) -> bool:
if num <= 0:
return False
while num >= 5:
if num % 2 != 0 and num % 3 != 0 and num % 5 != 0:
return False
else:
if num % 2 == 0:
num = num // 2
elif num % 3 == 0:
num = num // 3
else:
num = num //5
return True



# Leetcode 264：找出第 n 个丑数

编写一个程序，找出第 n 个丑数。



class Solution:
def nthUglyNumber(self, n: int) -> int:
#
# res = [1]*(n)
# minheap = [2,3,5]
# for i in range(1,n):
#     minheap = sorted(set(minheap))
#     res[i] = minheap.pop(0)
#     minheap.append(res[i]*2)
#     minheap.append(res[i]*3)
#     minheap.append(res[i]*5)
# return res[-1]

res = [1]
# 三指针
i2 = i3 = i5 = 0
for _ in range(1,n):
ugly = min(res[i2] * 2, res[i3] * 3, res[i5] * 5)
res.append(ugly)
if ugly == res[i2] * 2:
i2 +=1
if ugly == res[i3] * 3:
i3 +=1
if ugly == res[i5] * 5:
i5 +=1
return res[-1]


# Leetcode 313：超级丑数

示例:



class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
nums = [0 for _ in range(len(primes))]
result = [1]
for i in range(1,n):
ugly = min(result[nums[j]] * primes[j] for j in range(len(nums)))
result.append(ugly)
for k in range(len(nums)):
if ugly == result[nums[k]] * primes[k]:
nums[k] +=1
return result[-1]



# 后言（今天的日记）

17年就读于东莞XX学院化学工程与工艺专业，GitChat作者。Runsen的微信公众号是"Python之王"，因为Python入了IT的坑，从此不能自拔。公众号内容涉及Python，Java计算机、杂谈。干货与情怀同在。关注后回复「小白」即可免费获取原创的Python学习资料；喜欢的微信搜索：「Python之王」。个人微信号：RunsenLiu
09-09 588

04-24 7753
07-17 5154
07-28 365
12-14 1万+
01-06 975
06-15 2092
03-04 154