Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ac6cc5a

Browse files
Time: 82 ms (83.08%), Space: 16.5 MB (93.61%) - LeetHub
1 parent c464404 commit ac6cc5a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def nthUglyNumber(self, n: int) -> int:
3+
ugly = [0] * n # To store ugly numbers
4+
ugly[0] = 1 # 1 is the first ugly number
5+
6+
i2 = i3 = i5 = 0
7+
8+
next_2 = 2
9+
next_3 = 3
10+
next_5 = 5
11+
12+
for i in range(1, n):
13+
# Choose the smallest number among the next multiples
14+
next_ugly = min(next_2, next_3, next_5)
15+
ugly[i] = next_ugly
16+
17+
if next_ugly == next_2:
18+
i2 += 1
19+
next_2 = ugly[i2] * 2
20+
if next_ugly == next_3:
21+
i3 += 1
22+
next_3 = ugly[i3] * 3
23+
if next_ugly == next_5:
24+
i5 += 1
25+
next_5 = ugly[i5] * 5
26+
27+
return ugly[-1]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /