码迷,mamicode.com
首页 > 其他好文 > 详细

Ugly Number II

时间:2015-12-04 22:34:42      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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];
    }

 

Ugly Number II

标签:

原文地址:http://www.cnblogs.com/lasclocker/p/5020533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!