-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathUgly-Number-II.py
56 lines (56 loc) · 1.46 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
50
51
52
53
54
55
56
### Python Solution 1:
class Solution:
def isUgly(self, num: int) -> bool:
if num <1:
return False
while num%5 == 0:
num//=5
while num%3 == 0:
num//=3
while num%2 == 0:
num//=2
return num==1
def nthUglyNumber(self, n: int) -> int:
i = 0
num = 0
while i<n:
num+=1
if self.isUgly(num):
i+=1
return num
### Python Solution 2:
class Solution:
def nthUglyNumber(self, n):
# write code here
if n<=0:
return 0
dp = [0 for _ in range(n)]
dp[0] = 1
l_2 = 0
l_3 = 0
l_5 = 0
for i in range(1,n):
dp[i] = min(dp[l_2]*2,dp[l_3]*3,dp[l_5]*5)
if dp[l_2]*2<=dp[i]:
l_2+=1
if dp[l_3]*3<=dp[i]:
l_3+=1
if dp[l_5]*5<=dp[i]:
l_5+=1
return dp[n-1]
### Python Solution 3:
class Solution:
def nthUglyNumber(self, n: int) -> int:
res = 0
if n <= 0:
return 0
min_heap = []
heapq.heappush(min_heap,1)
for i in range(0,n):
res = heapq.heappop(min_heap)
while min_heap and res == min_heap[0]:
res = heapq.heappop(min_heap)
heapq.heappush(min_heap, res*2)
heapq.heappush(min_heap, res*3)
heapq.heappush(min_heap, res*5)
return res