264 Ugly Number II
264. Ugly Number II
1. Question
Write a program to find then
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include2, 3, 5
. For example,1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
Note that1
is typically treated as an ugly number, and n does not exceed 1690.
2. Implementation
(1) DP
思路: dp[i]表示第i个ugly number, 由于ugly number只有2, 3, 5这三个factor,当我们要找下一个ugly number时,我们需要取当前ugly number分别乘以2, 3, 5后最小的数,所以我们分别用三个变量index2, index3, index5找到对应的ugly number
3. Time & Space Complexity
Heap: 时间复杂度O(n), 空间复杂度O(n)
Last updated
Was this helpful?