把只包含質因子二、3和5的數稱做醜數(Ugly Number)

//超時java

public class Solution {code

public int GetUglyNumber_Solution(int index) {
    if(index==1)
        return 1;
    int sum=1;
    int n=1;
    int res=1;
    
    while(true){
        n++;
        if(f(n))
            sum++;
        if(sum==index) 
            return n;
    }
    
}

public boolean f(int n){
    
    int a[]={2,3,5};
    
    int len=a.length;
    
    int i=0;
    
    int sum=1;
    
    int temp = n;
    while(i<len){
        if(sum==n)
            return true;
        else if(sum>n)
            return false;
        else if(temp%a[i]==0){
            sum=sum*a[i];
            temp=temp/a[i];
        }
        else
            i++;
    }
    return false;
}

}io

//可行的方案class

import java.util.*;import

public class Solution {im

public int GetUglyNumber_Solution(int index) {

    if(index<1)
        return 0;
  int a[]=new int[index];
    a[0]=1;
    
    int i1=0,i2=0,i3=0;
    int temp1;
    for(int i=1;i<a.length;i++){
        temp1=Math.min(a[i1]*2,a[i2]*3);
        a[i]=Math.min(temp1,a[i3]*5);
        
        if(a[i]==a[i1]*2) i1++;
        if(a[i]==a[i2]*3) i2++;
        if(a[i]==a[i3]*5) i3++;
    }
                      
    return a[index-1];
}

}while

相關文章
相關標籤/搜索