Ugly number is a number that only have 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…
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { * @param k: The number k. * @return: The kth prime number as description. */ public long nthUglyNumber(int k) { if (k == 1) return 1; long unglyNumber = 0; PriorityQueue<Long> queue = new PriorityQueue<>(); queue.offer((long)2); queue.offer((long)3); queue.offer((long)5); for (int i = 1; i < k; i++){ unglyNumber = queue.poll(); if (unglyNumber % 2 == 0){ queue.offer(unglyNumber * 2); } else if (unglyNumber % 3 == 0) { queue.offer(unglyNumber * 2); queue.offer(unglyNumber * 3); } else { queue.offer(unglyNumber * 2); queue.offer(unglyNumber * 3); queue.offer(unglyNumber * 5); } } return unglyNumber; } };
|