leetcode笔记:Ugly Number II

本文介绍了一种高效算法来找出第N个丑数。丑数是指只包含2、3、5这三个质因数的正整数。文章通过示例详细解析了算法的设计思路,并提供了一段C++实现代码。

摘要生成于 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.

二. 题目分析

关于丑数的概念,可参考Ugly Number
从1开始的丑数为:1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … 该题的大意是,输入一个正整数n,返回第n个丑数,这要求比起Ugly Number一题是复杂了些。

事实上,在观察这些丑数组合时,无非是分成如下三种组合(其中,第一个乘数为上一次计算得出的丑数,第一个丑数为1,第二个乘数为2、3、5中的一个数):

(以2为乘数)1×2, 2×2, 3×2, 4×2, 5×2, 6×2, 8×2, …
(以3为乘数)1×3, 2×3, 3×3, 4×3, 5×3, 6×3, 8×3, …
(以5为乘数)1×5, 2×5, 3×5, 4×5, 5×5, 6×5, 8×5, …

于是,开辟一个存放n个丑数的数组,在每次迭代时,从三种乘法组合中选取积最小的丑数并放入数组。最后数组的最后一个元素即是所求的丑数。

三. 示例代码

class Solution
{
public:
    int nthUglyNumber(int n) {
        int* uglyNum = new int[n]; // 用于存放前n个丑数
        uglyNum[0] = 1;

        int factor2 = 2, factor3 = 3, factor5 = 5;
        int index2, index3, index5;
        index2 = index3 = index5 = 0;

        for(int i = 1; i < n; ++i)
        {
            // 取三组中的最小
            int minNum = min(factor2, factor3, factor5);
            uglyNum[i] = minNum;

            // 分三组计算
            if(factor2 == minNum)
                 factor2 = 2 * uglyNum[++index2];
            if(factor3 == minNum)
                 factor3 = 3 * uglyNum[++index3];
            if(factor5 == minNum)
                 factor5 = 5 * uglyNum[++index5];
        }
        int temp = uglyNum[n-1];
        delete [] uglyNum;
        return temp;
    }

private:
    // 求三个数的最小值
    int min(int a, int b, int c) {
        int minNum = a > b ? b : a;
        return minNum > c ? c : minNum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值