找出第n个ugly number
LeetCode第264题,Ugly Number II
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.
参考了一些网上的博客之后综合的一些想法,总结了一下。
思路
首先,uglynumber是只由235乘出来的数,所以一个数a是ugly数,
那么a乘(或者除)2(或3或5)也应该是uglynumber。
换言之现有小于M的所有uglynumber组成的数组ugly[],
那么接下来大于M的新uglynumber一定可以由数组ugly[]乘2(或3或5)生成。
其次,要找第n个uglynumber的最好可以按顺序依次生成新的uglynumber直到第n个。
综上有下面的算法(伪代码):