Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10 ugly numbers.
方法一:
根据[leetcode]
263. Ugly Number, https://blog.csdn.net/liuwenyou/article/details/100606158
显然我们可以加一个index来标记是第几个ugly number
public int nthUglyNumber(int n) {
if(n==0){
return 0;
}
int index=1;
int num=1;
while(index<=n){
if(isUgly(num)){
if(index==n){
return num;
}else{
num++;
index++;
}
}else{
num++;
}
}
return num;
}
private boolean isUgly(int m){
while(true){
if(m==1){
return true;
}else if(m%5==0){
m/=5;
}else if(m%3==0){
m/=3;
}else if(m%2==0){
m/=2;
}else{
return false;
}
}
}
显然,该算法复杂度很高,一个数一个数的检验是否为ugly number,当n较大时就会超出时间限制。
方法二:
用nums数组来顺序存储ugly number,下一数组元素由之前的nums数组中的元素乘以2或3或5,取且大于前一项的最小的数。
也不必每一个数组元素都要进行这一操作,我们分别用index2,index3,index5来表示要用于乘2,3,5的数组中元素的索引。
public int nthUglyNumber(int n) {
int []nums=new int[n];//nums数组按序存储ugly number
nums[0]=1;
int index2=0,index3=0,index5=0;//分别表示要用来*2 *3 *5的元素的索引
int i=1;
while(i<n){
int m2=nums[index2]*2;
int m3=nums[index3]*3;
int m5=nums[index5]*5;
nums[i]=Math.min(m2,Math.min(m3,m5));//取大于当前ugly number的最小的数
if(nums[i]==m2){
index2++;
}
if(nums[i]==m3){
index3++;
}
if(nums[i]==m5){
index5++;
}
i++;
}
return nums[n-1];
}