Ugly Number II 算法

本文介绍了一种算法来解决第N个丑数问题,涉及优先队列和质因数分解。通过使用2, 3, 5作为初始丑数,并利用这些质因数生成后续丑数,实现了一个Java方法 nthUglyNumber。

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

题目:Ugly Number II

Description:
Ugly number is a number that only have prime factors 2, 3 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…
Note that 1 is typically treated as an ugly number.

public class Solution {
    /**
     * @param n: An integer
     * @return: return a  integer as description.
     */
    public int nthUglyNumber(int n) {
        // write your code here
        Queue<Long> Q = new PriorityQueue<Long>();
        HashSet<Long> inQ = new HashSet<Long>();
        Long[] primes = new Long[3] ;
        primes[0] = Long.valueOf(2)  ;
        primes[1] = Long.valueOf(3)  ;
        primes[2] = Long.valueOf(5)  ;
       //Q.add(1);
       // inQ.add(1);
        for(int i = 0 ; i < 3 ; i++){
            Q.add(primes[i]);
            inQ.add(primes[i]);
        }
        
        Long numbers = Long.valueOf(1);
        for(int i=1 ; i < n ; i++){
            numbers = Q.poll() ;
            for(int j = 0 ; j < 3 ; j++){
                if(! inQ.contains(primes[j]*numbers)){
                     Q.add(primes[j]*numbers);
                     inQ.add(primes[j]*numbers);
                }
            }
        }
        return numbers.intValue() ;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值