Ugly Number II

本文介绍了一种高效算法,用于查找序列中的第N个丑数。丑数是指仅包含质因数2、3和5的正整数。文章详细阐述了如何利用优先队列和哈希集合来避免重复计算,确保算法的效率。通过实例展示了输入9时,输出的第9个丑数为10。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ugly number is a number that only have prime factors 23 and 5.

Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

Example

Example 1:

Input: 9
Output: 10

Example 2:

Input: 1
Output: 1

Challenge

O(n log n) or O(n) time.

Notice

Note that 1 is typically treated as an ugly number.

思路:就是所有的ugly number全部是由2,3,5以及他们生成的数,再乘以2,3,5生成的。然后用priorityqueue sort一下输出即可。注意用Long,防止溢出,最后cast成int

public class Solution {
    /**
     * @param n: An integer
     * @return: return a  integer as description.
     */
    public int nthUglyNumber(int n) {
        if(n <= 0) return -1;
        
        PriorityQueue<Long> pq = new PriorityQueue<Long>();
        HashSet<Long> hashset = new HashSet<Long>();
        Long[] primes = {1l,2l,3l,5l};
        
        for(int i = 0; i < primes.length; i++) {
            pq.add(primes[i]);
            hashset.add(primes[i]);
        }
        
        int count = 0;
        while(count < n) {
            long num = pq.poll();
            count++;
            if(count == n) {
                return (int)num;
            }
           for(int i = 0; i < primes.length; i++) {
               if(!hashset.contains(primes[i] * num)){
                   hashset.add(primes[i] * num);
                   pq.add(primes[i]*num);
               }
           }
        }
        return -1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值