【done】【特例】剑指offer——面试题34:丑数

力扣168,https://leetcode.cn/problems/chou-shu-lcof/description/
思路:
链接:https://www.nowcoder.com/questionTerminal/6aa9e04fc3794f68acf8778237ba065b?answerType=1&f=discussion
在这里插入图片描述

答案:

class Solution {
    public int nthUglyNumber(int n) {
        int[] array = new int[n]; 
        array[0] = 1;
        int t2 = 0, t3 = 0, t5 = 0;
        for (int i = 1; i < n; ++i) {
            array[i] = Math.min(array[t2] * 2, Math.min(array[t3] * 3, array[t5] * 5));
            if (array[i] == array[t2] * 2) {
                ++t2;
            }
            if (array[i] == array[t3] * 3) {
                ++t3;
            } 
            if (array[i] == array[t5] * 5) {
                ++t5;
            }
        }
        return array[n - 1];
    }
}

##Solution1:
最容易想到的,也是最不可能AC的

class Solution {
public:
    int GetUglyNumber_Solution(int index) { //输出第index个丑数
        int count = 1;
        if(index == 1)
            return count;
        for(int i = 2; ; i++){
            if(isUglyNum(i) == true){
                count++;
                if(count == index)
                    return i;
            }
        }
    }
    bool isUglyNum(int n) {
        while (n > 1) {
            for (int i = 2; i <= n; i++){
                if (n%i == 0){ //如果n能被i整除,i是因子,对i分小于等于5和大于5两种情况讨论
                    if (i <= 5) {
                        n /= i;
                        break;
                    }
                    if (i > 5)
                        return false;
                }
            }
        }
        return true;
    }
};

##Solution2:
记住这种查数的技巧!!!
答案参考网址:
[1]http://www.cnblogs.com/qqky/p/6964764.html
[2]https://www.nowcoder.com/profile/5810633/codeBookDetail?submissionId=16629921
解题思路:https://blog.csdn.net/lhanchao/article/details/52079323
本题定义三个变量,对于当前已排好序找到的最大的丑数M,记录恰乘2、乘3、乘5大于当前最大的丑数M的三个位置,然后求三个位置*2 *3 *5的最小值即为下一个丑数的值

class Solution {
public:
   int GetUglyNumber_Solution(int index) {
        if (index < 7) return index;
        vector<int> res(index);
        res[0] = 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];
    }
};

再感慨一句,别人的思路真牛逼啊~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值