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

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

时间:2015-08-19 14:52:31      阅读:107      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!