首页 > 其他 > 详细

LeetCode OJ 之 Ugly Number II (丑数-二)

时间:2015-08-19 14:50:44      阅读:299      评论: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.

思路:

参考:http://blog.csdn.net/u012243115/article/details/45222269

代码:

class Solution {
public:
    int nthUglyNumber(int n) 
    {
        if(n <= 0)
            return 0;
        int *uglyNum = new int[n]();
        int *uglyNum2 = uglyNum ;
        int *uglyNum3 = uglyNum ;
        int *uglyNum5 = uglyNum ;
        uglyNum[0] = 1;
        int count = 1;
        while(count < n)
        {
            int curUgly = min(min(*uglyNum2 * 2 , *uglyNum3 * 3) , *uglyNum5 * 5);
            uglyNum[count] = curUgly;
            while(*uglyNum2 * 2 <= curUgly)
                uglyNum2++;
            while(*uglyNum3 * 3 <= curUgly)
                uglyNum3++;
            while(*uglyNum5 * 5 <= curUgly)
                uglyNum5++;
            count++;
        }
        int result = uglyNum[n-1];
        delete [] uglyNum;
        return result;
        
    }
};


版权声明:转载请注明出处。

LeetCode OJ 之 Ugly Number II (丑数-二)

原文:http://blog.csdn.net/u012243115/article/details/47780157

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!