丑数

class Solution {
public:
//利用3个队列,分别保存乘以2、3、5的新数,每次只需判断每个
//队列最前面的数哪个最小,然后取出并把这个数乘上对应的因子压入
//三个队列中(这里要去重,具体看代码)
int GetUglyNumber_Solution(int index) {
if (index <= 0)
return 0;
--index;
queue<int> q2, q3, q5;
q2.push(2);
q3.push(3);
q5.push(5);
queue<int> *p;
int ans = 1;
while (index)
{
p = q2.front() < q3.front() ? &q2 : &q3;
p = (*p).front() < q5.front() ? p : &q5;
ans = (*p).front();
(*p).pop();
//flag来记录是那个队列取出的最小数
int flag = 0;
if(p == &q2)
flag = 1;
else if(p == &q3)
flag = 2;
else
flag = 3;
//这里的处理是去重,q3的不再压入q2,q5的不再压入q3和q2
switch(flag)
{
case 1:q2.push(ans * 2);//无break
case 2:q3.push(ans * 3);
case 3:q5.push(ans * 5);
}
--index;
}
return ans;
}
};

原文地址:https://www.cnblogs.com/mcyushao/p/9986504.html