python defaultdicth和最小堆和去重set的用法。

Python中defatultdict的概念、作用、常见用法举例 详解 - AlphaGeek - 博客

给你一个整数 n ,请你找出并返回第 n 个 丑数 。

丑数 就是质因子只包含 23 和 5 的正整数。

示例 1:

输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。

示例 2:

输入:n = 1
输出:1
解释:1 通常被视为丑数。
 1 class Solution:
 2     def nthUglyNumber(self, n: int) -> int:
 3         heap=[1]
 4         ans=set()
 5         cnt=0
 6         while cnt<n-1:
 7             min_val=heapq.heappop(heap)
 8             for factor in [2,3,5]:
 9                 if min_val*factor not in ans:
10                     ans.add(min_val*factor)
11                     heapq.heappush(heap,min_val*factor)
12             cnt=cnt+1
13         return heapq.heappop(heap)
14 
15             

 

 

 

posted @ 2026-01-27 11:08  suiyuemin520~  阅读(1)  评论(0)    收藏  举报