Premium ugly number! In the end it is the first of several ugly?
This question is based on the original number of ugly
lookingThe first fewNumber ugly
Failed attempts
Analyzing directly hit the table
all numbers in ugly 1690
Sure timeout benefits serving
No one judge
would need to find data rule the
Observation available
ugly excellent base number 2, 3, 5 is the number of still ugly - Simplify Analyzing
So ugly number may consist of the following list
2 | 1* 2 2 * 2 3 * 2 4 * 2 |
---|---|
3 | 1* 3 2 * 3 3 * 3 4 * 3 |
5 | 1* 2 2 * 2 3 * 2 4 * 2 |
practice:
- Maintenance three list - ugly2, ugly3, ugly5
respectively store ** now * 2, now * 3 , now * 5 ** - Take three at the beginning of the list Minimum- The number cnt number of ugly (the equivalent logarithmic ugly sorting process)
- Until cnt reaches the n - that is to take the number of the n-th ugly
code show as below:
class Solution {
public:
int nthUglyNumber(int n) {
list<long long> ugly2;
list<long long> ugly3;
list<long long> ugly5;
long long now = 1;
int cnt = 1;
while (cnt != n) {
ugly2.push_back(now * 2);
ugly3.push_back(now * 3);
ugly5.push_back(now * 5);
long long min2 = ugly2.front();
long long min3 = ugly3.front();
long long min5 = ugly5.front();
long long MIN = min(min2, min(min3, min5));
if (min2 == MIN) ugly2.pop_front();
if (min3 == MIN) ugly3.pop_front();
if (min5 == MIN) ugly5.pop_front();
now = MIN;
cnt++;
}
return now;
}
};