目录
一,题目描述
英文描述
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
中文描述
给你一个整数
n
,请你找出并返回第n
个 丑数 。丑数 就是只包含质因数
2
、3
和/或5
的正整数。
示例与说明
提示:
1 <= n <= 1690
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ugly-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二,解题思路
之前做过一个类似于动态规划的方法(后来才知道这是动态规划)。
- 给每个因数设置一个指针,比如indexOf2、indexOf3等,这个指针指向生成的丑数数组中对应位置,每次循环时,选出ans[indexOf2]*2、ans[indexOf3]等等中的最小的值,将这个值添加到ans数组中,并将对应的indexOfn指针后移一位。
- 若出现多个值相同,则他们的指针均后移一位。
这里采用堆的方法。
- 设计小根堆。最外层循环设置n,控制每次取出堆一个最小的丑数。
- 将取出的丑数分别乘上三个因子并存入堆中,继续下一次循环。
三,AC代码
C++
class Solution {
public:
struct cmp {
bool operator()(long a, long b) {
return a > b;
}
};
int nthUglyNumber(int n) {
int factors[] = {2, 3, 5};
priority_queue<long, vector<long>, cmp> heap;
unordered_set<long> record;
heap.push(1);
while (--n) {
long cur = heap.top();
heap.pop();
for (auto f : factors) {
long next = cur * f;
if (record.find(next) == record.end()) {
heap.push(next);
record.insert(next);
}
}
}
return int(heap.top());
}
};
Java
class Solution {
public int nthUglyNumber(int n) {
Set<Long> record = new HashSet<Long>();
int[] factors = {2, 3, 5};
PriorityQueue<Long> queue = new PriorityQueue<Long>(new Comparator<Long>(){
public int compare(Long a, Long b) {
return Long.compare(a, b);// !!!这里不能直接相减
}
});
// PriorityQueue<Long> queue = new PriorityQueue<Long>((a, b) -> (Long.compare(a, b)));
queue.offer(1L);
int ans = 0;
while (n-- > 0) {
long cur = queue.peek();
ans = (int) cur;
queue.poll();
for (int f : factors) {
long next = cur * f;
if (record.add(next)) {
queue.offer(next);
}
}
}
return ans;
}
}
四,解题过程
第一博
java版的搞了好长时间,最后发现是大数的处理问题。比较器中Long类型的数据最好不要直接相减去比较,而是通过Long.compare()获得结果。