剑指Offer_编程题_丑数

题目描述

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

AC代码

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index<7)
            return index;
		 int[] str=new int[index];
		 str[0]=1;
		 int p2=0,p3=0,p5=0;
		 
				 
		 for (int i = 1; i < str.length; i++) {
			str[i]=Math.min(Math.min(str[p2]*2,str[p3]*3 ), str[p5]*5);
					if(str[i]==str[p2]*2)
						p2++;
					if(str[i]==str[p3]*3)
						p3++;
					if(str[i]==str[p5]*5)
						p5++;
		}
		 
		 
	        return str[index-1];
    }
}

分析

在索引值小于7的时候,前6个丑数为1,2,3,4,5,6,我们设置起始数组为[1],后面的数依次是对于已知的丑数序列,后面的丑数一定是已知序列中的数字乘以2/3/5得到的。对当前序列中的数字乘2/3/5得到的数字中最小的数字才能放入序列。

原文地址:https://www.cnblogs.com/jiangyanblog/p/11668722.html