classSolution:defnthUglyNumber(self,n:int)->int:import heapq heap =[1] heapq.heapify(heap) res =0for _ inrange(n): res = heapq.heappop(heap)while heap and res == heap[0]: res = heapq.heappop(heap) a, b, c = res*2, res*3, res*5for t in[a, b, c]: heapq.heappush(heap, t)return res
Runtime: 244 ms, faster than 28.36% of Python3 online submissions for Ugly Number II.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Ugly Number II.
class Solution:
def nthUglyNumber(self, n: int) -> int:
dp = [0]*n
dp[0] = 1
i2 = i3 = i5 = 0
for i in range(1, n):
dp[i] = min(2*dp[i2], 3*dp[i3], 5*dp[i5])
if dp[i] == dp[i2]*2:
i2 += 1
if dp[i] == dp[i3]*3:
i3 += 1
if dp[i] == dp[i5]*5:
i5 += 1
return dp[-1]
var nthUglyNumber = function(n) {
const dp = new Array(n)
dp[0] = 1
let i2 = 0,
i3 = 0,
i5 = 0
for (let i = 1; i < n; i++) {
dp[i] = Math.min(2 * dp[i2], 3 * dp[i3], 5 * dp[i5])
if (dp[i] === 2 * dp[i2]) {
i2++
}
if (dp[i] === 3 * dp[i3]) {
i3++
}
if (dp[i] === 5 * dp[i5]) {
i5++
}
}
return dp[n - 1]
};
func min(a, b, c int) int {
var m int
if a < b {
m = a
} else {
m = b
}
if c < m {
return c
} else {
return m
}
}
func nthUglyNumber(n int) int {
dp := make([]int, n)
dp[0] = 1
var i2, i3, i5 int
for i := 1; i < n; i++ {
dp[i] = min(dp[i2]*2, dp[i3]*3, dp[i5]*5)
if dp[i] == dp[i2]*2 {
i2++
}
if dp[i] == dp[i3]*3 {
i3++
}
if dp[i] == dp[i5]*5 {
i5++
}
}
return dp[n-1]
}