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);
}
}
本文介绍了一种优化算法,用于快速找到第n个丑数,丑数是仅包含质因数2、3、5的正整数。通过维护三个有序链表并按最小值递增的方式,实现了一次遍历即可找到目标丑数,适用于需要大量生成或查找丑数的场景。
721

被折叠的 条评论
为什么被折叠?



