leetcode 原题链接:https://leetcode.com/problems/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.
简要分析:
最直观的想法就是,设定一个计数器cnt,从1开始找,对每一个数进行判断,是则计数器加1,否则不做处理;但是这么做的话会导致需要去判断每一个数字是不是丑数。计算量就比较大了。
然而,我们是否能够只去找丑数,而不管其他的数呢? leetcode上的提示信息表示这是可以的。可以利用数组存储已经得到的丑数,并利用他们计算得到新的丑数,因为新的丑数只能是由比他自身小的丑数乘2或者乘3或者乘5得到。
实现代码:
#include <iostream>
using namespace std;
class Solution
{
public:
int nthUglyNumber(int n)
{
if (n < 1)
return 0;
int *uglyNumbers = new int[n];
uglyNumbers[0] = 1;
int nextUglyNumber = 1;
int *ugly2 = uglyNumbers;
int *ugly3 = uglyNumbers;
int *ugly5 = uglyNumbers;
while (nextUglyNumber < n)
{
//cout << uglyNumbers[nextUglyNumber-1] << endl;
int min = min3(*ugly2 * 2, *ugly3 * 3, *ugly5 * 5);
uglyNumbers[nextUglyNumber] = min;
while (*ugly2 * 2 <= uglyNumbers[nextUglyNumber]) { ++ugly2; }
while (*ugly3 * 3 <= uglyNumbers[nextUglyNumber]) { ++ugly3; }
while (*ugly5 * 5 <= uglyNumbers[nextUglyNumber]) { ++ugly5; }
++nextUglyNumber;
}
int nthUgly = uglyNumbers[nextUglyNumber - 1];
delete[]uglyNumbers;
return nthUgly;
}
int min3(int num1, int num2, int num3)
{
int min = 0;
min = num1 < num2 ? num1 : num2;
min = min < num3 ? min : num3;
return min;
}
};
int main()
{
Solution st;
cout << st.nthUglyNumber(1100) << endl;
return 0;
}