-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUglyNumberII.py
40 lines (32 loc) · 1005 Bytes
/
UglyNumberII.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution:
def nthUglyNumber(self, n: int) -> int:
nums = [1]
i2 = i3 = i5 = 0
for i in range(1, n):
next_num = min(
nums[i2] * 2,
nums[i3] * 3,
nums[i5] * 5
)
nums.append(next_num)
if next_num == nums[i2] * 2:
i2 += 1
if next_num == nums[i3] * 3:
i3 += 1
if next_num == nums[i5] * 5:
i5 += 1
return nums[n - 1]
# heap solution: O(nlogn)
# min_heap = [1]
# seen = set()
# i = 0
# while i < n:
# cur = heapq.heappop(min_heap)
# if cur in seen:
# continue
# heapq.heappush(min_heap, cur * 2)
# heapq.heappush(min_heap, cur * 3)
# heapq.heappush(min_heap, cur * 5)
# seen.add(cur)
# i += 1
# return cur