一. 题目描述
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.
二. 题目分析
关于丑数的概念,可参考Ugly Number:
从1开始的丑数为:1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … 该题的大意是,输入一个正整数n,返回第n个丑数,这要求比起Ugly Number一题是复杂了些。
事实上,在观察这些丑数组合时,无非是分成如下三种组合(其中,第一个乘数为上一次计算得出的丑数,第一个丑数为1,第二个乘数为2、3、5中的一个数):
(以2为乘数)1×2, 2×2, 3×2, 4×2, 5×2, 6×2, 8×2, …
(以3为乘数)1×3, 2×3, 3×3, 4×3, 5×3, 6×3, 8×3, …
(以5为乘数)1×5, 2×5, 3×5, 4×5, 5×5, 6×5, 8×5, …
于是,开辟一个存放n个丑数的数组,在每次迭代时,从三种乘法组合中选取积最小的丑数并放入数组。最后数组的最后一个元素即是所求的丑数。
三. 示例代码
class Solution
{
public:
int nthUglyNumber(int n) {
int* uglyNum = new int[n]; // 用于存放前n个丑数
uglyNum[0] = 1;
int factor2 = 2, factor3 = 3, factor5 = 5;
int index2, index3, index5;
index2 = index3 = index5 = 0;
for(int i = 1; i < n; ++i)
{
// 取三组中的最小
int minNum = min(factor2, factor3, factor5);
uglyNum[i] = minNum;
// 分三组计算
if(factor2 == minNum)
factor2 = 2 * uglyNum[++index2];
if(factor3 == minNum)
factor3 = 3 * uglyNum[++index3];
if(factor5 == minNum)
factor5 = 5 * uglyNum[++index5];
}
int temp = uglyNum[n-1];
delete [] uglyNum;
return temp;
}
private:
// 求三个数的最小值
int min(int a, int b, int c) {
int minNum = a > b ? b : a;
return minNum > c ? c : minNum;
}
};