A number is ugly
if its prime factors is a subset of ${2, 3, 5}$. We are required to find the $n$-th ugly
number
Intuition
Each ugly number is generated from a previous ugly number by multiplying $2$, $3$ or $5$.
Approach
We use three pointers index_2
, index_3
and index_5
to record the index of previous ugly number. For example, $4$ is generated from $2$ by multiplying $2$, so the index index_2
is the index of 2
.
Then, we take the minimum of three generated numbers:
|
|
Finally, we need to update the pointers so that there is no duplication.
Complexity
Time complexity: iterate once. $$O(n)$$
Space complexity: Use a vector to store the result. $$O(n)$$
Code
|
|