【LeetCode】264. Ugly Number II

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.

Show Hint 

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

     

    思路:所有的ugly number都是由1开始,乘以2/3/5生成的。

    只要将这些生成的数排序即可获得,自动排序可以使用set

    这样每次取出的第一个元素就是最小元素,由此再继续生成新的ugly number.

    class Solution {
    public:
        int nthUglyNumber(int n) {
            set<long long> order;
            order.insert(1);
            int count = 0;
            long long curmin = 0;
            while(count < n)
            {
                curmin = *(order.begin());
                order.erase(order.begin());
                order.insert(curmin * 2);
                order.insert(curmin * 3);
                order.insert(curmin * 5);
                count ++;
            }
            return (int)curmin;
        }
    };

    posted @ 2015-08-22 12:13  陆草纯  阅读(537)  评论(0编辑  收藏  举报