264. 丑数 II
编写一个程序,找出第 n 个丑数。
丑数就是质因数只包含 2, 3, 5 的正整数。
思路
1.丑数:把只包含质因子2,3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但7、14不是,因为它们包含质因子7。 习惯上我们把1当做是第一个丑数。
2.当寻找第N个,第K个时候,使用堆是最好的
3.这里用大根堆来寻找第N大的丑数,用hashmap来判断求出来的数是否已经存在。
错误
因为N在乘上因子之后可能会溢出,所以这路的键用Long类型。
完整代码
public int nthUglyNumber(int n) {
PriorityQueue<Long> heap = new PriorityQueue<Long>();
HashMap<Long, Integer> hash = new HashMap<Long, Integer>();
heap.add(1L);
hash.put(1L, 1);
int[] factor = new int[] {2,3,5};
long curUgly = 1L;
long newUgly;
for(int i = 0; i < n; i++) {
curUgly = heap.poll();
for (int f : factor) {
newUgly = curUgly * f;
if(!hash.containsKey(newUgly)) {
heap.add(newUgly);
hash.put(newUgly, 1);
}
}
}
return (int)curUgly;
}
313. 超级丑数
编写一段程序来查找第 n 个超级丑数。
超级丑数是指其所有质因数都是长度为 k 的质数列表 primes 中的正整数。
思路
这个问题和上面的问题是一样的,只是因数未知
完整代码
public int nthSuperUglyNumber(int n, int[] primes) {
PriorityQueue<Long> heap = new PriorityQueue<Long>();
HashMap<Long, Integer> hash = new HashMap<Long, Integer>();
heap.add(1L);
hash.put(1L, 1);
long curNum = 1L;
long newNum;
for(int i = 0; i < n; i++) {
curNum = heap.poll();
for (int p : primes) {
newNum = curNum * p;
if(!hash.containsKey(newNum)) {
hash.put(newNum, 1);
heap.add(newNum);
}
}
}
return (int)curNum;
注意在返回结果时候要做类型转换。