【LeetCode】264. Ugly Number II

Ugly Number IIthis

Write a program to find the n-th ugly number.spa

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.code

Note that 1 is typically treated as an ugly number.blog

Show Hint 排序

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

     

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

    只要将这些生成的数排序便可得到,自动排序可使用setget

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

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

    相关文章
    相关标签/搜索