264. Ugly Number II #341
-
Topics: An ugly number is a positive integer whose prime factors are limited to Given an integer Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We can use a dynamic programming approach. We'll maintain an array to store the ugly numbers and use three pointers to multiply by 2, 3, and 5. Let's implement this solution in PHP: 264. Ugly Number II <?php
function nthUglyNumber($n) {
$uglyNumbers = array_fill(0, $n, 0);
$uglyNumbers[0] = 1;
$i2 = $i3 = $i5 = 0;
$next2 = 2;
$next3 = 3;
$next5 = 5;
for ($i = 1; $i < $n; $i++) {
$nextUgly = min($next2, $next3, $next5);
$uglyNumbers[$i] = $nextUgly;
if ($nextUgly == $next2) {
$i2++;
$next2 = $uglyNumbers[$i2] * 2;
}
if ($nextUgly == $next3) {
$i3++;
$next3 = $uglyNumbers[$i3] * 3;
}
if ($nextUgly == $next5) {
$i5++;
$next5 = $uglyNumbers[$i5] * 5;
}
}
return $uglyNumbers[$n - 1];
}
// Example usage:
$n1 = 10;
echo nthUglyNumber($n1); // Output: 12
$n2 = 1;
echo nthUglyNumber($n2); // Output: 1
?> Explanation:
This solution ensures that we generate the sequence of ugly numbers efficiently, focusing only on valid ugly numbers and skipping non-ugly numbers. |
Beta Was this translation helpful? Give feedback.
We can use a dynamic programming approach. We'll maintain an array to store the ugly numbers and use three pointers to multiply by 2, 3, and 5.
Let's implement this solution in PHP: 264. Ugly Number II