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.
之前有个题目是判断是一个数是否为丑数,按照常规思路应该是从1开始顺序查找判断是否为丑数,但是这样效率不高;因此维护3个队列,分别为乘2的丑数,乘3的丑数和乘5丑数的队列,丑数一定是前面2,3,5乘以2,3,5得到的数字。因此每次从队列首部取出三个数字中最小的数字作为第k个丑数,同时乘以2,3,5放入队尾。
class Solution {
public:
int getMin(int a,int b,int c)
{
int temp = a>b?b:a;
return temp>c?c:temp;
}
int nthUglyNumber(int n) {
list<int> q2;
list<int> q3;
list<int> q5;
int count = 1;
int num = 1;
while(count != n)
{
q2.push_back(2*num);
q3.push_back(3*num);
q5.push_back(5*num);
int a = q2.front();
int b = q3.front();
int c = q5.front();
int min = getMin(a,b,c);
if(min == a) q2.pop_front();
if(min == b) q3.pop_front();
if(min == c) q5.pop_front();
++count;
num = min;
}
return num;
}
};