Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ugly-number-ii.cpp 2.19 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-12-04 01:02 +08:00 . Update ugly-number-ii.cpp
// Time: O(n)
// Space: O(n)
// DP solution. (12ms)
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> uglies(n);
uglies[0] = 1;
int f2 = 2, f3 = 3, f5 = 5;
int idx2 = 0, idx3 = 0, idx5 = 0;
for (int i = 1; i < n; ++i) {
int min_val = min(min(f2, f3), f5);
uglies[i] = min_val;
if (min_val == f2) {
f2 = 2 * uglies[++idx2];
}
if (min_val == f3) {
f3 = 3 * uglies[++idx3];
}
if (min_val == f5) {
f5 = 5 * uglies[++idx5];
}
}
return uglies[n - 1];
}
};
// Time: O(n)
// Space: O(1)
// Heap solution. (148ms)
class Solution2 {
public:
int nthUglyNumber(int n) {
long long ugly_number = 0;
priority_queue<long long , vector<long long>, greater<long long>> heap;
heap.emplace(1);
for (int i = 0; i < n; ++i) {
ugly_number = heap.top();
heap.pop();
if (ugly_number % 2 == 0) {
heap.emplace(ugly_number * 2);
} else if (ugly_number % 3 == 0) {
heap.emplace(ugly_number * 2);
heap.emplace(ugly_number * 3);
} else {
heap.emplace(ugly_number * 2);
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
}
}
return ugly_number;
}
};
// BST solution.
class Solution3 {
public:
int nthUglyNumber(int n) {
long long ugly_number = 0;
set<long long> bst;
bst.emplace(1);
for (int i = 0; i < n; ++i) {
ugly_number = *bst.cbegin();
bst.erase(bst.cbegin());
if (ugly_number % 2 == 0) {
bst.emplace(ugly_number * 2);
} else if (ugly_number % 3 == 0) {
bst.emplace(ugly_number * 2);
bst.emplace(ugly_number * 3);
} else {
bst.emplace(ugly_number * 2);
bst.emplace(ugly_number * 3);
bst.emplace(ugly_number * 5);
}
}
return ugly_number;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助