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...
Example
If n=9, return 10.
Challenge
O(n log n) or O(n) time.
Notice
Note that 1 is typically treated as an ugly number.
public class Solution {
/**
* @param n: An integer
* @return: the nth prime number as description.
*/
public int nthUglyNumber(int n) {
if(n <= 0) return 0;
if(n == 1) return 1;
int[] res = new int[n];
res[0] = 1;
int index2 = 0, index3 = 0, index5 = 0;
for(int i = 1; i < n; i++){
int res2 = 2*res[index2], res3 = 3*res[index3], res5 = 5*res[index5];
int tmp = Math.min(Math.min(res2, res3), res5);
if(tmp == res2) index2++;
if(tmp == res3) index3++;
if(tmp == res5) index5++;
res[i] = tmp;
}
return res[n-1];
}
}
//还有一种方法是用PriorityQueue
class Solution {
/**
* @param n an integer
* @return the nth prime number as description.
*/
public int nthUglyNumber(int n) {
// Write your code here
Queue<Long> pq = new PriorityQueue<Long>();
// 用一个set来避免有重复的元素出现
// 每次都弹出最小的值,然后用这个值去乘235,只要没有重复就加进去
// 用pq的好处是避免了去找最小值,pq每次poll出来的都是满足条件的ugly number的最小值
// 但是每次都会加三个数进pq
HashSet<Long> set = new HashSet<Long>();
Long[]base = new Long[3];
base[0] = (long)2;
base[1] = (long)3;
base[2] = (long)5;
Long res = (long)1;
for(int i = 0; i < 3; i++) {
pq.offer(base[i]);
set.add(base[i]);
}
for(int i = 1; i < n; i++){
res = pq.poll();
for(int j = 0; j < 3; j++) {
long tmp = base[j] * res;
if(set.contains(tmp))
continue;
set.add(tmp);
pq.offer(tmp);
}
}
return res.intValue();
}
};