题目:把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
思路:一个丑数成以2/3/5,得到的还是一个丑数;有3个对列pos2/pos3/pos5,每次都取最小的数,放到数组中【小于7的数都是丑数】。
代码:
public class ArrayLimit {
public static void main(String[] args) {
ArrayLimit al=new ArrayLimit();
System.out.println(al.GetUglyNumber_Solution(8));
}
public int GetUglyNumber_Solution(int index) {
if (index < 7) {
return index;
}
int[] res = new int[index];
res[0] = 1;
int pos2 = 0;// 2的对列
int pos3 = 0;// 3的对列
int pos5 = 0;// 5的对列
// 一个丑数*2/3/5还是丑数
for (int i = 1; i < index; i++) {
res[i] = Math.min(Math.min(res[pos2] * 2, res[pos3] * 3), res[pos5] * 5);
if (res[i]==res[pos2] * 2) {
pos2++;
}
if (res[i]==res[pos3] * 3) {
pos3++;
}
if (res[i]==res[pos5] * 5) {
pos5++;
}
}
return res[index-1];
}}



京公网安备 11010502036488号