zoukankan      html  css  js  c++  java
  • 4. 丑数 II

    描述

    设计一个算法,找出只含素因子235 的第 n 小的数。

    符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

    我们可以认为 1 也是一个丑数。

    样例

    样例 1:

    输入:9
    输出:10
    

    样例 2:

    输入:1
    输出:1

    题解:

    class Solution {
    public:
        /**
         * @param n: An integer
         * @return: return a  integer as description.
         */
        int nthUglyNumber(int n) {
            priority_queue <long long, vector<long long>, greater<long long> > heap;
            heap.push(1LL);
    
            set<long long> seen;
            seen.insert(1LL);
            
            vector<int> factors({2,3,5});
    
            long long currUgly = 1LL, newUgly;
    
            for (int i = 0; i < n; ++i) {
                // 每次弹出当前最小丑数
                currUgly = heap.top();
                heap.pop();
                // 生成新的丑数
                for(int &f: factors) {
                    newUgly = currUgly * f;
                    if (seen.count(newUgly) == 0) {
                        seen.insert(newUgly);
                        heap.push(newUgly);
                    }
                }
            }
            return (int)currUgly;
        }
    };
    
  • 相关阅读:
    构建高性能的读服务
    Redis基础入门
    基于TCP实现简单的聊天室
    递归

    Go标准库Cond
    排序(冒泡,选择,插入,快速)
    链表
    队列
    Golang实现RPC
  • 原文地址:https://www.cnblogs.com/deepend/p/14199269.html
Copyright © 2011-2022 走看看