264. Ugly Number II
Problem description:
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and n does not exceed 1690.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Solution:
Let’s say we have an result array that contains every ugly number in it.result[i]: ith ugly number
Now, how do we get the next ugly number, result[i+1]
? The next ugly number must be one of these,result[i]*2
, result[i]*3
, result[i]*5
. That is to say, if we know which to multiply, we can get i+1th
ugly number.
We can use three different pointer to indicate three different counter for 2, 3, and 5. Each time we compare the product of these, and the least one is next ugly number.
1 | class Solution { |