#include <vector>
#include <queue>
#include <iostream>
using namespace std;
/*
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, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
*/
// using three queues is better than using one vector.
int nthUglyNumber(int n) {
if(n == 1) return 1;
queue<int> TwoPrimes;
TwoPrimes.push(2);
queue<int> ThreePrimes;
ThreePrimes.push(3);
queue<int> FivePrimes;
FivePrimes.push(5);
while(n > 1) {
int currMin = min(TwoPrimes.front(), min(ThreePrimes.front(), FivePrimes.front()));
if(currMin == TwoPrimes.front()) {
TwoPrimes.pop();
TwoPrimes.push(2 * currMin);
ThreePrimes.push(3 * currMin);
FivePrimes.push(5 * currMin);
} else if(currMin == ThreePrimes.front()) {
ThreePrimes.pop();
ThreePrimes.push(3 * currMin);
FivePrimes.push(5 * currMin);
} else {
FivePrimes.pop();
FivePrimes.push(5 * currMin);
}
n--;
if(n == 1) return currMin;
}
}
int main(void) {
cout << nthUglyNumber(10) << endl;
}
LeetCode 264. Ugly Number II
最新推荐文章于 2025-04-12 19:07:09 发布
本文介绍了一种使用三个队列高效求解第N个丑数的方法。丑数是指只包含2、3、5这三个质因数的正整数。通过不断生成新的丑数并维护三个独立的队列,确保每次都能找到最小的下一个丑数。
759

被折叠的 条评论
为什么被折叠?



