Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
找到第n个ugly number, 第一我们维护ugly number从小到大的顺序,类似给三个有序链表l1, l2, l3排序,假设已经找到第k个ugly number, 那么第k+1个ugly number就是Math.min(l1 * 2, l2 * 3, l3 * 5)。代码如下:
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
找到第n个ugly number, 第一我们维护ugly number从小到大的顺序,类似给三个有序链表l1, l2, l3排序,假设已经找到第k个ugly number, 那么第k+1个ugly number就是Math.min(l1 * 2, l2 * 3, l3 * 5)。代码如下:
public class Solution {
public int nthUglyNumber(int n) {
List<Integer> list = new ArrayList<Integer>();
int a = 0;
int b = 0;
int c = 0;
list.add(1);
while(list.size() < n) {
int tem = Math.min(Math.min(list.get(a) * 2, list.get(b) * 3), list.get(c) * 5);
list.add(tem);
if(tem == list.get(a) * 2) a ++;
if(tem == list.get(b) * 3) b ++;
if(tem == list.get(c) * 5) c ++;
}
return list.get(n - 1);
}
}