【剑指Offer系列】49-丑数(优先队列-小顶堆)

题目: 只包含因子2、3、5的数为丑数。求第1500个丑数

给你一个整数 n ,请你找出并返回第 n 个 丑数 。
说明:丑数是只包含质因数 2、3 和/或 5 的正整数;1 是丑数。

示例 1:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

方式一:暴力-容易超时

public class Main49 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        System.out.println(kthulgy(k, new ArrayList<Integer>()));
    }

    private static int kthulgy(int k, List<Integer> list) {
        if (k <= 0)
            return -1;
        list.add(1);
        int temp = 2;//2-无穷的找,直到找够k个
        while (list.size() != k){
            int value = temp;
            while (value % 2 == 0){//10,5   ;14 7
                value /= 2;
            }
            while (value % 3 == 0){
                value /= 3;
            }
            while (value % 5 == 0){//1
                value /=5 ;
            }
            if (value == 1){//1   ;  7
                list.add(temp);
            }
            ++temp;
        }
        return list.get(k-1);
    }
}

方式二: 优先队列-小顶堆

class Solution {
    public int nthUglyNumber(int n) {
        Queue<Long> queue = new PriorityQueue<>();
        Set<Long> set = new HashSet<>();
        int[] factorArr = { 2, 3, 5 };
        queue.add(1L);
        set.add(1L);

        Long res = 1L;
        for (int i = 1; i <= n; i++) {
            res = queue.poll();
            for (int factor : factorArr) {
                Long next = res * factor;
                if (set.contains(next)) {
                    continue;
                }
                queue.add(next);
                set.add(next);
            }
        }
        return res.intValue();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值