[leetcode] Ugly Number II

题目:

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

分析:可参考ugly number,本题可用小顶堆或TreeSet求解,虽然可以AC,但相对于DP来说,运行时间还是很长,下面介绍DP求解过程:

用数组uglyNums存储每个ugly number,

用变量factor2存储乘2得到的最小ugly number,用变量factor3存储乘3得到的最小ugly number,用变量factor5存储乘5得到的最小ugly number,

另外引入变量index2,index3,index5,其中

factor2 = 2 * uglyNums[index2];

factor3 = 3 * uglyNums[index3];

factor5 = 5 * uglyNums[index5];

可以使用下图说明此意:

第一步:

第二步:

第三步:

第四步:

第五步:

Java代码如下:

    public int minAll(int factor2, int factor3, int factor5) {
        return Math.min(Math.min(factor2, factor3), factor5);
    }
    public int nthUglyNumber(int n) {
        int factor2 = 2, factor3 = 3, factor5 = 5;
        int index2 = 0, index3 = 0, index5 = 0;
        int[] uglyNums = new int[n];
        uglyNums[0] = 1;
        for(int i = 1; i < n; i++) {
            int min = minAll(factor2, factor3, factor5);
            uglyNums[i] = min;
            if(min == factor2) {
                factor2 = 2 * uglyNums[++index2];
            }
            if(min == factor3) {
                factor3 = 3 * uglyNums[++index3];
            }
            if(min == factor5) {
                factor5 = 5 * uglyNums[++index5];
            }
        }
        return uglyNums[n-1];
    }
原文地址:https://www.cnblogs.com/lasclocker/p/5020533.html