import static jdk.nashorn.internal.objects.NativeMath.min;
public class E49UglyNumber {
//找到第n个丑数,视1为第一个丑数
public static int getUglyNumber(int index){
if (index <= 0)
return -1;
//维护一个数组存储从小到大排序的丑数
int[] uglyNumbers = new int[index];
uglyNumbers[0] = 1;
int minMultiply2 = 0;
int minMultiply3 = 0;
int minMultiply5 = 0;
for (int i = 1; i < index; i ++){
uglyNumbers[i] = min(uglyNumbers[minMultiply2] * 2,
uglyNumbers[minMultiply3] * 3, uglyNumbers[minMultiply5] * 5);
//由于当前比较的丑数不断增大,minMultiply之前的丑数不必再检测
while(uglyNumbers[minMultiply2] * 2 <= uglyNumbers[i])
minMultiply2 ++;
while(uglyNumbers[minMultiply3] * 3 <= uglyNumbers[i])
minMultiply3 ++;
while(uglyNumbers[minMultiply5] * 5 <= uglyNumbers[i])
minMultiply5 ++;
}
return uglyNumbers[index - 1];
}
private static int min(int number1, int number2, int number3){
int min = (number1 < number2) ? number1 : number2;
min = (min < number3) ? min : number3;
return min;
}
//测试用例
public static void main(String[] args){
for (int i = 0; i <= 1500; i ++)
System.out.println(E49UglyNumber.getUglyNumber(i));
}
}
丑数(Java实现)
最新推荐文章于 2024-07-30 20:41:10 发布