剑指offer 33. 丑数

原题

题目:

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

Reference Answer

思路分析

把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
方法一思路:
1、res用来存放排好序的丑数。每一个丑数 n 都是从小于 n 的丑数 乘以 2,3,5 中得来的。
2、所以每次只需要考虑 <= n的丑数中,没有加入res的值,例如为(n-1)*5,那么只需要比较(n-1)*5,(n-1)*2,(n-1)*3的值,取最小存入res.

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index <= 0:
            return 0
        index_two = index_three = index_five = 0
        res = [1]
        while len(res) < index:
            temp = min(res[index_two] * 2, res[index_three] * 3, res[index_five] * 5)
            if not temp in res:
                res.append(temp)
            if temp % 2 == 0:
                index_two += 1
            if temp % 3 == 0:
                index_three += 1
            if temp % 5 == 0:
                index_five += 1
        return res[index-1]

上述代码可以把判定条件改进地更直观一些:

C++ Version:

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
        if (index <= 0){
            return 0;
        }
        vector<int> res(index);
        int base2 = 0, base3 = 0, base5 = 0;
        for(int i = 6; i < index; i++){
            res[i] = min(res[base2]*2, min(res[base3]*3, res[base5]*5));
            while(res[base2]*2 <= res[i]){
                base2 ++;
            }
            while(res[base3]*3 <= res[i]){
                base3++;
            }
            while(res[base5]*5 <= res[i]){
                base5++;
            }
        }
        return res[index-1];
    }
};

Python Version:

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index <= 0:
            return 0
        res = [1]
        base2 = base3 = base5 = 0
        for i in range(1, index):
            res.append(min(res[base2]*2, res[base3]*3, res[base5]*5))
            while res[base2]*2 <= res[i]:
                base2 += 1
            while res[base3]*3 <= res[i]:
                base3 += 1
            while res[base5]*5 <= res[i]:
                base5 += 1
        return res[index-1]

Note:

  • 对于 C++ 版本,需要注意的是判定 base2, base3, base5 更新的条件包含等于情况,即:while(res[base2]*2 <= res[i]) ;
  • 对于 Python 版本,注意首先判定 index <= 0 的情况,因为后面默认 index = 0 时,结果对于为 1;

参考文献:

[1] https://blog.csdn.net/Lynette_bb/article/details/75579740

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值