264. Ugly Number II
LeetCode 264. Ugly Number II
Description
Given an integer n
, return the nth
ugly number.
Ugly number is a positive number whose prime factors only include 2
, 3
, and/or 5
.
Example 1:
Example 2:
Constraints:
1 <= n <= 1690
Tags
Math, Dynamic Programming, Heap
Solution
We define an array dp. Each dp[i]
represents the ith ugly number. The edge case is dp[1]=1
, which is the smallest ugly number. Then, we initialize 3 pointers p2, p3, p5
starting from 1. The transferring function is dp[i] = min(dp[p2]*2, dp[p3]*3, dp[p5]*5)
. After updating, we compare dp[i]
with each of the three. The pointer of the one which is equal to dp[i]
will be moving one step forward. Finally, we return the result dp[n]
.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?