題目出處
難度
Medium
個人範例程式碼
class Solution:
def nthUglyNumber(self, n: int) -> int:
if not n:
return -1
visited = set([1])
heap = [1]
for _ in range(n):
cur = heapq.heappop(heap)
for factor in [2, 3, 5]:
new = cur * factor
if new not in visited:
visited.add(new)
heapq.heappush(heap, new)
return cur
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
算法說明
這裡我們用 minheap 來解,因為要不斷的輸出最小,
透過 minheap 減少我們搜尋的時間。
input handling
如果 input 是 0,return -1 (題目沒有要求要處理)
Boundary conditions
for 迴圈控制數量