【leetcode】丑数相关题

这篇博客介绍了如何使用优先队列(小根堆)解决两种数列问题:264.丑数II和313.超级丑数。丑数是指只包含质因数2、3和5的正整数,而超级丑数则是由给定质数组合而成的数,按升序排列。博主通过创建优先队列和哈希集合,实现了依次找到第n个丑数和超级丑数的高效算法。
摘要由CSDN通过智能技术生成

264.丑数II

class Solution {
    int[] nums = new int[]{2, 3, 5};
    public int nthUglyNumber(int n) {
        Queue<Long> q = new PriorityQueue<>();
        Set<Long> s = new HashSet<>();
        q.add(1L);
        s.add(1L);
        for (int i = 1; i <= n; i++) {
            long x = q.poll();
            if (i == n) return (int) x;
            for (int num : nums) {
                if (!s.contains(num * x)) {
                    s.add(num * x);
                    q.add(num * x);
                }
            }
        }
        return -1;
    }
}

优先队列(小根堆)解法
起始先将最小丑数 1 放入队列
每次从队列取出最小值 x,然后将 xx 所对应的丑数 2x、3x 和 5x进行入队。
对步骤 2 循环多次,第 n 次出队的值即是答案。
为了防止同一丑数多次进队,我们需要使用数据结构 Set 来记录入过队列的丑数。

313.超级丑数

题目意思::数组里给的都是质数,将这些质数进行各种组合乘起来(每个质数可以不用也可用多次),将结果进行排序,把第n个数返回

class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        Set<Long> s = new HashSet<>();
        Queue<Long> q = new PriorityQueue<>();
        s.add(1L);
        q.add(1L);
        while (n-- > 0) {
            long x = q.poll();
            if(n==0) return (int) x;
            for (int i : primes) {
                if (!s.contains(i * x)) {
                    s.add(i * x);
                    q.add(i * x);
                }
            }
        }
        return -1;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值