让我们先来看看丑数的定义:
丑数:是只包含质因数2、3、5的正整数。
即%2或%3,%5==0;
一、判断丑数的方法很简单。
递归法迭代法
class solution { public : boolisugly (intn )//递归方法if ) n==1) return true; if (! n )返回假; if(n%2==0) returnisugly ) n/2; if(n%5==0) returnisugly ) n/5; if(n%3==0) returnisugly ) n/3; else return false; }boolisugly(intm ) ) /迭代法if ) m=0) return false; while(m1 ) if ) m%2==0) m=m/2; ELSEif(m%3==0) m=m/3; ELSEif(m%5==0) m=m/5; else return false; } return m==1; }; 二.寻找第n个丑数
3指针动态规划
class solution { public : intnthuglynumber (intn ) { int m=0; vectorint res; res.push_back(1); int i2=0,i3=0,i5=0; for(intI=1; in; I () m=min(RES[I2]*2,min ) res[i5]*5,res[i5]*5) res.push_back(m; if(m==RES[i2]*2) I2; if(m==RES[I3]*3) i3; if(m==RES[I5]*5) i5; } return res[n-1]; }; 通过优先队列实现
class solution { public : intnthuglynumber (intn ) ) { priority_queuedouble,vectordouble,greaterdouble q; q.push(1; double ans=1,i=1; wile(I=n ) ) q.push ) ans*2; q.push(ans*3); q.push(ans*5); ans=q.top (; q.pop (; while (! q.empty(ans==q.top ) ) { q.pop; (I ); } return ans; };