712222. Ugly Number II
Medium
Ugly Number II
Summary
An ugly number is a positive integer whose decimal representation contains only digits that are 1, 2, 3, 4, or 5. Write a function to find the nth ugly number.
Detailed Explanation
To solve this problem, we can use a dynamic programming approach. We start by defining an array ugly of size n, where ugly[i] represents the i-th ugly number.
We initialize ugly[0] = 1, since the first ugly number is 1.
Then, for each i > 0, we calculate ugly[i] as the smallest multiple of 2, 3, or 5 that is greater than ugly[i-1]. This is because an ugly number can only be a multiple of 2, 3, or 5 if it's not already been accounted for.
Here's a step-by-step breakdown:
- Initialize
ugly[0] = 1. - For each
i > 0:- Calculate the smallest multiple of 2 that is greater than
ugly[i-1]. Let this bemultiple_2. - Calculate the smallest multiple of 3 that is greater than
ugly[i-1]. Let this bemultiple_3. - Calculate the smallest multiple of 5 that is greater than
ugly[i-1]. Let this bemultiple_5. - Set
ugly[i]to the minimum ofmultiple_2,multiple_3, andmultiple_5.
- Calculate the smallest multiple of 2 that is greater than
This approach ensures that we generate all ugly numbers up to the n-th one.
Time complexity: O(n) Space complexity: O(1)
Optimized Solutions
Java
public int nthUglyNumber(int n) {
int[] ugly = new int[n];
ugly[0] = 1;
for (int i = 1; i < n; i++) {
int multiple_2 = 2 * ugly[i-1], multiple_3 = 3 * ugly[i-1], multiple_5 = 5 * ugly[i-1];
ugly[i] = Math.min(Math.min(multiple_2, multiple_3), multiple_5);
}
return ugly[n-1];
}