class Solution:
"""
@param: n: An integer
@return: the nth prime number as description.
"""
def nthUglyNumber(self, n):
factor = (2,3,5)
ugly = [1]
i, j, k = 0, 0, 0 # i, j, k 分别跟踪 2,3,5 的下一个因子
while len(ugly) < n:
next = min(ugly[i] * 2, ugly[j] * 3, ugly[k] * 5)
if next == ugly[i] * 2:
i += 1
if next == ugly[j] * 3:
j += 1
if next == ugly[k] * 5:
k += 1
ugly.append(next)
return ugly[-1]
public class Solution {
/*
* @param n: An integer
* @return: the nth prime number as description.
*/
public int nthUglyNumber(int n) {
// 使用一个min heap,每次取出最小值,乘上【2,3,5】,再offer,循环n次,
// 最小值就是解,时间复杂度O(nlogn)
if (n == 1) return 1;
PriorityQueue<Long> pq = new PriorityQueue<>();
pq.offer((long)1);
for (int i = 0; i < n - 1; ++i) {
long currMin = pq.poll();
// 需要去重
while (! pq.isEmpty() && pq.peek() == currMin) pq.poll();
pq.offer(currMin * 2);
pq.offer(currMin * 3);
pq.offer(currMin * 5);
}
return (int)(long)(pq.peek());
}
}
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
# min heap solution
if n == 1:
return 1
pq = [1]
for i in range(n - 1):
currMin = heapq.heappop(pq)
while pq and pq[0] == currMin:
heapq.heappop(pq)
heapq.heappush(pq, currMin * 2)
heapq.heappush(pq, currMin * 3)
heapq.heappush(pq, currMin * 5)
return pq[0]