Ugly number is a number that only have prime factors 2
, 3
and 5
.
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Example
Example 1:
Input: 9
Output: 10
Example 2:
Input: 1
Output: 1
Challenge
O(n log n) or O(n) time.
Notice
Note that 1
is typically treated as an ugly number.
思路:就是所有的ugly number全部是由2,3,5以及他们生成的数,再乘以2,3,5生成的。然后用priorityqueue sort一下输出即可。注意用Long,防止溢出,最后cast成int
public class Solution {
/**
* @param n: An integer
* @return: return a integer as description.
*/
public int nthUglyNumber(int n) {
if(n <= 0) return -1;
PriorityQueue<Long> pq = new PriorityQueue<Long>();
HashSet<Long> hashset = new HashSet<Long>();
Long[] primes = {1l,2l,3l,5l};
for(int i = 0; i < primes.length; i++) {
pq.add(primes[i]);
hashset.add(primes[i]);
}
int count = 0;
while(count < n) {
long num = pq.poll();
count++;
if(count == n) {
return (int)num;
}
for(int i = 0; i < primes.length; i++) {
if(!hashset.contains(primes[i] * num)){
hashset.add(primes[i] * num);
pq.add(primes[i]*num);
}
}
}
return -1;
}
}