classSolution:defisUgly(self, n:int)->bool:if n ==0:returnFalse
nums =[2,3,5]for i in nums:while n % i ==0:
n /= i
return n ==1
264. 丑数 II
解法一:py中的堆结构
import heapq
classSolution:defnthUglyNumber(self, n:int)->int:
h =[1]
mp =[1]
nums =[2,3,5]for i inrange(n -1):
x = heapq.heappop(h)for j in nums:
t = j * x
if t notin mp:
heapq.heappush(h, t)
mp.append(t)return heapq.heappop(h)if __name__ =='__main__':
x = Solution()print(x.nthUglyNumber(10))
解法二:动态规划+三指针
classSolution:defnthUglyNumber(self, n:int)->int:
nums =[2,3,5]
dp =[1]
ptr =[0,0,0]
l =0while l < n:
minX =min(dp[ptr[0]]*2, dp[ptr[1]]*3, dp[ptr[2]]*5)
dp.append(minX)
l +=1for i inrange(3):if minX == dp[ptr[i]]* nums[i]:
ptr[i]+=1return dp.pop()if __name__ =='__main__':
x = Solution()for i inrange(10):print(x.nthUglyNumber(i))