Middle-题目81:264. Ugly Number II

本文介绍了一种求解第N个丑数的有效算法。丑数定义为仅包含2、3、5作为质因数的正整数。通过维护三个索引分别对应2、3、5的倍数序列,逐步构建出前N个丑数。

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

题目原文:
Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.
题目大意:
求第n个丑陋数。
丑陋数指的是质因数只有2,3,5的正整数。注意1是丑数。
题目分析:
其实本题是前面的Middle-题目41的退化情况,相当于求列表[2,3,5]下的超级丑数。因此算法本质与那道题完全一样,只是这次只维护2,3,5三个素数的索引值即可。
源码:(language:java)

public class Solution {
    public int nthUglyNumber(int n) {
        int l1=1,l2=1,l3=1;
        int a,b,c;
        int[] uglyNumber = new int[n+1];
        uglyNumber[1] = 1;
        for(int i = 2;i<=n;i++) {
            a=uglyNumber[l1]*2;
            b=uglyNumber[l2]*3;
            c=uglyNumber[l3]*5;
            int min = min(a,b,c);
            if(min==a)
                l1++;
            if(min==b)
                l2++;
            if(min==c)
                l3++;
            uglyNumber[i]=min;
        }
        return uglyNumber[n];
    }
    private  int min(int a, int b, int c) {
        if(a<=b && a<=c)
            return a;
        else if(b<=a && b<=c)
            return b;
        else 
            return c;
    }
}

成绩:
7ms,beats 96.36%,众数9ms,12.39%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值