LeetCode 0264. Ugly Number II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0264. Ugly Number II

Description

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return the nth ugly number.

 

Example 1:

Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.

Example 2:

Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

 

Constraints:

  • 1 <= n <= 1690

Solutions

Solution 1

PythonJavaC++GoJavaScriptC#
class Solution: def nthUglyNumber(self, n: int) -> int: h = [1] vis = {1} ans = 1 for _ in range(n): ans = heappop(h) for v in [2, 3, 5]: nxt = ans * v if nxt not in vis: vis.add(nxt) heappush(h, nxt) return ans(code-box)

Solution 2

PythonJavaC++Go
class Solution: def nthUglyNumber(self, n: int) -> int: dp = [1] * n p2 = p3 = p5 = 0 for i in range(1, n): next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 dp[i] = min(next2, next3, next5) if dp[i] == next2: p2 += 1 if dp[i] == next3: p3 += 1 if dp[i] == next5: p5 += 1 return dp[-1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !