• 剑指offer49 丑数


    1.正常就是数一个个遍历 然后看哪个是丑数?

    // 面试题49:丑数
    // 题目:我们把只包含因子2、3和5的数称作丑数(Ugly Number)。求按从小到
    // 大的顺序的第1500个丑数。例如6、8都是丑数,但14不是,因为它包含因子7。
    // 习惯上我们把1当做第一个丑数。
    
    #include <iostream>
    
    // ====================算法1的代码====================
    //不用额外的内存,直接计算
    bool IsUgly(int number)//判断是不是丑数
    {
        while (number % 2 == 0)
            number /= 2;
        while (number % 3 == 0)
            number /= 3;
        while (number % 5 == 0)
            number /= 5;
    
        return (number == 1) ? true : false;
    }
    
    int GetUglyNumber_Solution1(int index)
    {
        if (index <= 0)
            return 0;
    
        int number = 0;
        int uglyFound = 0;
        while (uglyFound < index)//从头到尾开始计算
        {
            ++number;
    
            if (IsUgly(number))
                ++uglyFound;
        }
    
        return number;
    }

    2.牛客网好厉害

       int GetUglyNumber_Solution(int index) {
            if (index < 7)
                return index;
            vector<int> res(index);
            res[0] = 1;//习惯上称第一个丑数为1
            int t2 = 0, t3 = 0, t5 = 0, i;
            for (i = 1; i < index; ++i)
            {
                res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5));
                if (res[i] == res[t2] * 2)t2++;
                if (res[i] == res[t3] * 3)t3++;
                if (res[i] == res[t5] * 5)t5++;
            }
            return res[index - 1];
        
        }
  • 相关阅读:
    acwing272. 最长公共上升子序列
    哈夫曼编码简单实现
    Linked List Sorting
    jmeter-线程组
    css-书写规范
    mysql-踩坑记录
    vue-npm install
    css-选择器
    js-process对象
    linux-常用命令
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11402892.html
Copyright © 2020-2023  润新知