题目
思路及代码
直接对丑数进行存储。将丑数数组中的数依次乘以2,3,5,将最小的数存入数组,并将乘 2 3 5的下标+1,后续最小的丑数应该从2 3 5对应下标的丑数乘2 3 5中产生。
import java.lang.Math;
public class Solution {
public int GetUglyNumber_Solution(int index) {
if( index <=0) return 0;
int[] uglyNumber = new int [index];
uglyNumber[0]= 1;
int u2 = 0,u3= 0,u5=0;
for(int i= 1;i<index;i++){
int min = Math.min(uglyNumber[u2]*2,Math.min(uglyNumber[u3]*3,uglyNumber[u5]*5));
uglyNumber[i]= min;
if(min== uglyNumber[u2]*2) {
// uglyNumber[i]= min;
u2++;
}
if(min== uglyNumber[u3]*3) {
// uglyNumber[i]= min;
u3++;
}
if(min== uglyNumber[u5]*5) {
// uglyNumber[i]= min;
u5++;
}
}
return uglyNumber[index-1];
}
}
import java.lang.Math;
public class Solution {
public int GetUglyNumber_Solution(int index) {
if( index <=0) return 0;
int[] uglyNumber = new int [index];
uglyNumber[0]= 1;
int u2 = 0,u3= 0,u5=0;
for(int i= 1;i<index;i++){
int min = Math.min(uglyNumber[u2]*2,Math.min(uglyNumber[u3]*3,uglyNumber[u5]*5));
//uglyNumber[i]= min;
if(min== uglyNumber[u2]*2) {
uglyNumber[i]= min;
u2++;
}
if(min== uglyNumber[u3]*3) {
uglyNumber[i]= min;
u3++;
}
if(min== uglyNumber[u5]*5) {
uglyNumber[i]= min;
u5++;
}
}
return uglyNumber[index-1];
}
}