题目:Ugly Number II
Description:
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…
Note that 1 is typically treated as an ugly number.
public class Solution {
/**
* @param n: An integer
* @return: return a integer as description.
*/
public int nthUglyNumber(int n) {
// write your code here
Queue<Long> Q = new PriorityQueue<Long>();
HashSet<Long> inQ = new HashSet<Long>();
Long[] primes = new Long[3] ;
primes[0] = Long.valueOf(2) ;
primes[1] = Long.valueOf(3) ;
primes[2] = Long.valueOf(5) ;
//Q.add(1);
// inQ.add(1);
for(int i = 0 ; i < 3 ; i++){
Q.add(primes[i]);
inQ.add(primes[i]);
}
Long numbers = Long.valueOf(1);
for(int i=1 ; i < n ; i++){
numbers = Q.poll() ;
for(int j = 0 ; j < 3 ; j++){
if(! inQ.contains(primes[j]*numbers)){
Q.add(primes[j]*numbers);
inQ.add(primes[j]*numbers);
}
}
}
return numbers.intValue() ;
}
}