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.
题解:
题目要求求n个丑数,但是丑数的个数不超过1690,因此我可以猜测该题目的对算法复杂度要求不超过O(n^2),实质上求丑数的方法有很多,比如用优先队列,但是在这里我想到一个用来记录下标的方法:假如现在要求第k个丑数,分别记录下上次乘以2,乘以3,乘以5所得到的丑数是多少,这次将对应的数再分别乘2,乘3,乘5,取最小值,就是当前第k个丑数的值。这样的算法复杂度是O(n)是目前想到的比较好的算法。用三个下标,这样做的目的是保证每次都得到大于第k-1个丑数的最小的丑数。
代码:
class Solution { public: int nthUglyNumber(int n) { vector<int> res; res.push_back(1); int ind2,ind3,ind5; ind2 = ind3 = ind5 = 0; for(int i = 1;i < n;i++) { res.push_back(min(res[ind2]*2,min(res[ind3]*3,res[ind5]*5))); if(res[i]==res[ind2]*2) ind2++; if(res[i]==res[ind3]*3) ind3++; if(res[i]==res[ind5]*5) ind5++; } return res[n-1]; } };