Leetcode 313: Super Ugly Number (超级丑数)

  1. Super Ugly Number
    Medium
    A super ugly number is a positive integer whose prime factors are in the array primes.
    Given an integer n and an array of integers primes, return the nth super ugly number.
    The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

Example 1:

Input: n = 12, primes = 2,7,13,19

Output: 32

Explanation: 1,2,4,7,8,13,14,16,19,26,28,32 is the sequence of the first 12 super ugly numbers given primes = 2,7,13,19.

Example 2:

Input: n = 1, primes = 2,3,5

Output: 1

Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = 2,3,5.

Constraints:

1 <= n <= 105

1 <= primes.length <= 100

2 <= primesi <= 1000

primesi is guaranteed to be a prime number.

All the values of primes are unique and sorted in ascending order.

解法1:用Heap做。注意去重可以用topNode.product != uglysindex。

cpp 复制代码
struct Node {
    int prime;
    int index;
    long long product;
    Node(int pri, int id, long long pro) : prime(pri), index(id), product(pro) {}
    bool operator < (const Node & node) const {
        return product >= node.product;
    }
};

class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        int primesCount = primes.size();
        vector<long long> uglys(n + 1, 0);
        vector<int> indexes(primesCount, 1);
        priority_queue<Node> minHeap;
        uglys[1] = 1;
        int index = 1;
        for (int i = 0; i < primesCount; i++) {
            minHeap.push(Node(primes[i], 1, primes[i])); //1 * primes[i] = primes[i]
        }

        while (index <= n) {
            int minV = INT_MAX;
            Node topNode = minHeap.top();
            minHeap.pop();
            if (topNode.product != uglys[index]) {
                if (index < n) {
                    uglys[++index] = topNode.product;
                }
                else break;
            }
            minHeap.push(Node(topNode.prime, topNode.index + 1, uglys[topNode.index + 1] * topNode.prime));
        }
        return (int)uglys[n];
    }
};
相关推荐
灯澜忆梦7 小时前
【面向对象编程C++】| 基础语法
java·c++·算法
小蒋观天下7 小时前
专项方案:大场景港口AI安防、多干扰环境下的算法调优与落地实操
人工智能·深度学习·算法·安全·机器学习·计算机视觉·ai大模型
Evand J7 小时前
【电机滤波例程5】渐消因子自适应扩展卡尔曼滤波(EKF),MATLAB。PMSM负载突变下的状态估计。附下载链接
算法·matlab
H.莓飛7 小时前
【数据结构】二叉树_OJ题
linux·开发语言·数据结构·算法
好想像大佬一样能够ak所有8 小时前
Leetcode35.搜索插入位置
数据结构·算法·leetcode
aqiu1111118 小时前
【C++算法打怪专栏】LeetCode 165. 比较版本号(双指针与字符串流法)
c++·算法·leetcode
黄金龙PLUS8 小时前
如何基于置换算法来设计对称加密算法
算法·网络安全·密码学·哈希算法·同态加密
不会就选b8 小时前
算法日常・每日刷题--<动态规划>14
算法
赛博守夜人8 小时前
跨境业务与出海合规之九:海外买量投放与营销虚假流量(Ad Fraud):跨国机房群控与归因欺诈识别算法
算法·安全
镜子AI10 小时前
教培机构AI推荐系统实战:概念漂移检测算法——为什么“去年有效的推荐今年可能失效“
人工智能·算法