LeetCode OJ 之 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.

思路:

參考: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;
        
    }
};


posted @ 2017-05-22 14:51  zsychanpin  阅读(156)  评论(0编辑  收藏  举报