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;
        }
    };
    
  • 相关阅读:
    Path Sum
    Binary Tree Level Order Traversal II
    Jump Game
    leedcode 刷题-V2
    (2016 年) githup 博客地址 : https://github.com/JMWY/MyBlog
    算法分类总结
    剑指 Offer 题目汇总索引
    LeedCde 题解目录
    趣味算法总目录
    常用
  • 原文地址:https://www.cnblogs.com/deepend/p/14199269.html
Copyright © 2011-2022 走看看