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 小时前
LeetCode CodeTop 82.删除排序链表中的重复元素Ⅱ
算法·leetcode·链表
189228048617 小时前
NV114固态MT29F16T08EWLEHD6-MES:E
人工智能·算法·缓存·性能优化
Tairitsu_H7 小时前
[LC优选算法#4] 滑动窗口 | 串联所有单词的⼦串 | 最⼩覆盖⼦串
c++·算法·滑动窗口
devilnumber7 小时前
Java 二分查找(二分算法)详解 + 实战运用 + 核心坑点
java·开发语言·算法
洛水水7 小时前
【力扣100题】84.字符串解码
算法·leetcode·职场和发展
嵌入式ZYXC7 小时前
第9篇:《面试题:ADC前端为什么要加运放跟随器?什么情况下可以不加?》
stm32·单片机·嵌入式硬件·面试·职场和发展
MicroTech20257 小时前
量子隐形传态路线的瓶颈与突破,微算法科技(MLGO)以技术创新助力量子通信长距离组网
科技·算法·量子计算
洛水水7 小时前
【力扣100题】89.下一个排列
数据结构·算法·leetcode
洛水水7 小时前
【力扣100题】90.寻找重复数
算法·leetcode·职场和发展
鱼子星_7 小时前
【数据结构】排序的拓展——快速排序的生态多样性与归并排序沾染文件操作
c语言·数据结构·算法