# [LintCode] Ugly Number

linspiration

## Problem

Ugly number is a number that only have factors 3, 5 and 7.
Design an algorithm to find the Kth ugly number. The first 5 ugly numbers are 3, 5, 7, 9, 15 ...

## Example

If K=4, return 9.

## Note

``````    //primes = [3, 5, 7];
//Q = {3, 5, 7};
//map = {(3, true), (5, true), (7, true)};
//num = 3: Q.add(9, 15, 21); map.put(9,, 15,, 21, true);
//num = 5: Q.add(15->no, 25, 35), map.put(25,, 35, true);
//num = 7: Q.add(25->no, 35->no, 49), map.put(49, true);
//k = 4: loop i stops, num = 9; ...; return num = 9;
``````

## Solution

``````class Solution {
Queue<Long> Q = new PriorityQueue<Long>();
HashMap<Long, Boolean> map = new HashMap<Long, Boolean>();
Long[] primes = new Long[3];
primes[0] = Long.valueOf(3);
primes[1] = Long.valueOf(5);
primes[2] = Long.valueOf(7);
for (int i = 0; i < 3; i++) {
map.put(primes[i], true);
}
Long num = Long.valueOf(0);
for (int i = 0; i < k; i++) {
num = Q.poll();
for (int j = 0; j < 3; j++) {
if (!map.containsKey(primes[j] * num)) {
map.put(primes[j] * num, true);
}
}
}
return num;
}
}

``````