寻找第n个丑数

博客介绍了丑数的定义,即仅含因子2、3和5的数。设计算法求第n个丑数,采用空间换时间的方法,创建长度为n的数组,根据丑数特性比较得出最新丑数,算过一次后因子基数加一避免重复计算,并给出了Java代码实现。

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

Description

Ugly number is a number that only have 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...

 

通过空间代价来提升时间复杂度。

创建一个数组,长度为n,根据n位的丑数是前面的丑数乘2、乘3或乘5所得,比较所得最小的数就是最新的丑数。

算过一次之后,该因子的基数加一,避免重复计算。

 

public class Solution {
    /**
     * @param n: An integer
     * @return: the nth prime number as description.
     */
    public int nthUglyNumber(int n) {
        // write your code here
        int[] ugly = new int[n];
        ugly[0] = 1;
        int nextUglyIndex = 1;

        int mul2 = 0;
        int mul3 = 0;
        int mul5 = 0;
        int min = 0;
        while(nextUglyIndex<n){
            min = compare_min(ugly[mul2]*2,ugly[mul3]*3,ugly[mul5]*5);
            ugly[nextUglyIndex] = min;
            while(ugly[mul2]*2<=ugly[nextUglyIndex]){
                mul2++;
            }
            while(ugly[mul3]*3<=ugly[nextUglyIndex]){
                mul3++;
            }
            while(ugly[mul5]*5<=ugly[nextUglyIndex]){
                mul5++;
            }

            nextUglyIndex++;


        }
        int result = ugly[n - 1];
        return result;
    }
    public int compare_min(int a,int b,int c){
        if(a<=b){
            if(a<=c)
                return a;
            return c;
        }else if(c<=b){
            return c;
        }
        return b;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值