题目:
丑数 II:编写一个程序,找出第 n 个丑数。 丑数就是质因数只包含 2, 3, 5 的正整数。
思路:
使用最小堆来实现,借助哈希表保证了结果的唯一性。
程序:
import heapq class Solution: def nthUglyNumber(self, n: int) -> int: myHeap = [] current_ugly = 1 heapq.heappush(myHeap, current_ugly) findOut = set() findOut.add(current_ugly) elements = [2, 3, 5] index = 1 while index <= n: current_ugly = heapq.heappop(myHeap) for element in elements: new_ugly = current_ugly * element if new_ugly in findOut: continue else: findOut.add(new_ugly) heapq.heappush(myHeap, new_ugly) index += 1 return current_ugly