思路,设置三个队列,一个放乘以2的数,一个放乘以3的数,一个放乘以5的数,每次选择三个队列里面的最小的数,添加到存放有序丑数的数组中。
代码如下:
package myproject;
//丑数
import java.util.Scanner;
public class test06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
System.out.println(GetUglyNumber_Solution(m));
}
public static int GetUglyNumber_Solution(int index) {
int[] arr = new int[index];
arr[0] = 1;
int count = 0;
int i2 = 0;
int i3 = 0;
int i5 = 0;
int tmp ;
while(count<index-1) {
tmp = min(arr[i2]*2,min(arr[i3]*3,arr[i5]*5)); //用来选择三个队列中的最小数,而且能保证是丑数
if(tmp == arr[i2]*2) i2++; //以下三行代码用来判断重复
if(tmp == arr[i3]*3) i3++;
if(tmp == arr[i5]*5) i5++;
arr[++count]=tmp; //向数组中存放丑数
}
return arr[index-1]; //获取第n个丑数
}
public static int min(int a,int b) {
return (a>b)?b:a;
}
}
注:能保证是丑数,是因为丑数是通过乘以2,乘以三,乘以五得到的。
方法2 :
package myproject;
import java.util.Scanner;
//丑数问题
public class test05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.println(GetUglyNumber_Solution(a));
}
public static int GetUglyNumber_Solution(int index) {
while(index<=0) {
return 0;
}
int number = 0;
int findUgly = 0;
while(findUgly<index) {
++number;
if(IsUgly(number)) {
++findUgly;
}
}
return number;
}
public static boolean IsUgly(int number) {
// TODO Auto-generated method stub
while(number%2==0)
number/=2;
while(number%3==0)
number/=3;
while(number%5==0)
number/=5;
return (number == 1) ? true:false;
}
}
该方法时间复杂度较高,但便于理解丑数问题