#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 发布