zoukankan      html  css  js  c++  java
  • 剑指offer——丑数(c++)

    题目描述
    只包含质因子2、3和5的数称作丑数(UglyNumber)。例如6、8都是丑数,但14不是,因为它包含质因子7,习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

    思路:
    1、逐个判断
    逐个判断每个整数是不是丑数。根据丑数的定义,丑数只能被2,3,5整除,也就是说,如果一个数能被2整除,连续除以2;如果能被3整除,连续除以3;如果能被5整除,连续除以5,如果最后得到1,那么这个数就是丑数,否则就不是。

    2、创建数组保存已经找到的丑数
    第一种方法效率比较低,因为该方法对每个数无论是丑事还是非丑数,都进行了计算判断,这在一定程度上是浪费。

    根据丑数的定义,后面的丑数应该是前面丑数的2,3,5的倍数结果,因此我们可以创建一个数组,里面的数字是排好序的丑数,每一个丑数都是前面的丑数乘以2,3,5得到。

    那么如何保证排序呢?假设当前数组中最大的丑数为M,我们把已有的每个丑数分别乘以2,3,5(实际上并不需要对每个丑数做乘积,只需每次保存上一次的位置即可),分别得到第一个乘以2后大于M的结果2M,第一个乘以3后大于M的结果3M,第一个乘以5后大于M的结果3M,那么下一个丑数就是2M,3M,5M的最小者。

    代码:
    class Solution {
    public:
    int GetUglyNumber_Solution(int index) {
    if(index <= 0)
    return 0;
    vector<int> nums(index);
    nums[0] = 1;
    int nextIndex = 1;
    int index2 = 0, index3 = 0, index5 = 0;
    while(nextIndex < index){
    nums[nextIndex] = min(nums[index2]*2, min(nums[index3]*3, nums[index5]*5));
    if(nums[index2]*2 <= nums[nextIndex]) ++index2;
    if(nums[index3]*3 <= nums[nextIndex]) ++index3;
    if(nums[index5]*5 <= nums[nextIndex]) ++index5;
    ++nextIndex;
    }
    return nums[index-1];
    }
    };
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    ---------------------

  • 相关阅读:
    浅析椭圆曲线加密算法(ECC)
    比特币原理——交易与UTXO
    比特币白皮书-学习笔记
    python SMTP邮件发送
    Linux : Forks()
    IS: [=Burp Suite No.4=]Burp Suite /Scanner/ and /Intruder/
    IS: [=Burp Suite No.3=]Burp Suite /Target/ and /Spider/
    IS: [=Burp Suite No.2=]Burp Suite SSL and advanced options
    IS: [=Burp Suite No.1=]Burp Suite install and configuration
    IS: WMIC command use
  • 原文地址:https://www.cnblogs.com/ly570/p/11109344.html
Copyright © 2011-2022 走看看