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:
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 is typically treated as an ugly number.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?