forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUgly Number II.py
49 lines (47 loc) · 1.73 KB
/
Ugly Number II.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
41
42
43
44
45
46
47
48
49
# Runtime: 354 ms (Top 28.01%) | Memory: 13.9 MB (Top 55.93%)
import heapq
class Solution:
def nthUglyNumber(self, n: int) -> int:
h1, h2, h3 = [], [], []
heapq.heappush(h1, 1)
heapq.heappush(h2, 1)
heapq.heappush(h3, 1)
ugly_number = 1
last_ugly_number = 1
count = 1
while count < n:
if 2 * h1[0] <= 3 * h2[0] and 2 * h1[0] <= 5 * h3[0]:
# pop from h1
x = heapq.heappop(h1)
ugly_number = 2 * x
if ugly_number == last_ugly_number:
# do nothing
continue
count+=1
last_ugly_number = ugly_number
heapq.heappush(h1, ugly_number)
heapq.heappush(h2, ugly_number)
heapq.heappush(h3, ugly_number)
elif 3 * h2[0] <= 2 * h1[0] and 3 * h2[0] <= 5 * h3[0]:
# pop from h2
x = heapq.heappop(h2)
ugly_number = 3 * x
if ugly_number == last_ugly_number:
continue
count+=1
last_ugly_number = ugly_number
heapq.heappush(h1, ugly_number)
heapq.heappush(h2, ugly_number)
heapq.heappush(h3, ugly_number)
else:
# pop from h3
x = heapq.heappop(h3)
ugly_number = 5 * x
if ugly_number == last_ugly_number:
continue
count+=1
last_ugly_number = ugly_number
heapq.heappush(h1, ugly_number)
heapq.heappush(h2, ugly_number)
heapq.heappush(h3, ugly_number)
return last_ugly_number