leetcode [264] - Ugly Number II

该博客主要围绕查找第n个丑数的程序展开。丑数是只能被2、3、5整除的正数,通常将1视为丑数。程序思路是利用指针,后面的丑数在前面丑数基础上乘以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

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note: 

1. 1 is typically treated as an ugly number.

2. n does not exceed 1690.

题目大意:

  程序输出第n个丑数。(丑数指只能被2,3,5整除的数)

理  解:

  可以很容易发现,后面的丑数都是在前面的丑数基础上乘以2或者3或者5.

  设置三个指针分别指向2,3,5对应的"基数",比较当前三个数的大小,选择最小的数作为当前的丑数。

  【参考了其他人的想法,指针这个方法真的很奇妙。】

代  码 C++:

  

class Solution {
public:
    int nthUglyNumber(int n) {
        int *uglyNumber = new int[n];
        uglyNumber[0]=1;
        int nextUglyIndex = 1;
        
        int *uglyNumberOfTwo = uglyNumber;
        int *uglyNumberOfThree = uglyNumber;
        int *uglyNumberOfFive = uglyNumber;
        int min;
        
        while(nextUglyIndex<n){
            min = (((*uglyNumberOfTwo)*2) < ((*uglyNumberOfThree)*3))? ((*uglyNumberOfTwo)*2):((*uglyNumberOfThree)*3);
            min = (min < *uglyNumberOfFive*5)?min:*uglyNumberOfFive*5;
            uglyNumber[nextUglyIndex]=min;
            
            if(*uglyNumberOfTwo*2<=min)
                uglyNumberOfTwo++;
            if(*uglyNumberOfThree*3<=min)
                uglyNumberOfThree++;
            if(*uglyNumberOfFive*5<=min)
                uglyNumberOfFive++;
            
            nextUglyIndex++;
        }
        return uglyNumber[n-1];
    }
};

 

转载于:https://www.cnblogs.com/lpomeloz/p/10922166.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值