- 丑数 II
编写一个程序,找出第 n 个丑数。
丑数就是质因数只包含 2, 3, 5 的正整数。
示例:
用堆竟然炸了,我裂开来
class Solution {
public:
int nthUglyNumber(int n) {
priority_queue<int> q;
if (n==1 || n==2 || n==3) {
return n;
}
vector<int> v;
q.push(-1);
v.push_back(-1);
while (v.size() < n) {
int temp = q.top();
if (v.size() > 0 && v[v.size() - 1] != temp) {
cout << -1 * temp << endl;
v.push_back(temp);
}
q.pop();
q.push(temp*2);
q.push(temp*3);
q.push(temp*5);
}
return -1 * v[n-1];
}
};
tql
class Solution {
public:
int nthUglyNumber(int n) {
int s2 = 0,s3 = 0,s5 = 0;//三条线各自的起始指针
int t2,t3,t5;
int dp[n];
dp[0] = 1;
for(int i=1;i<n;i++){
t2 = dp[s2]*2;
t3 = dp[s3]*3;
t5 = dp[s5]*5;
dp[i] = min(min(t2,t3),t5);
if(dp[i] == t2){
s2++;
}
if(dp[i] == t3){
s3++;
}
if(dp[i] == t5){
s5++;
}
}
return dp[n-1];
}
};