剑指 Offer 49. 丑数

2020-07-29

1.题目描述

我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。

2.题解

合并三个集合

3.代码

class Solution {
    
    
public:
    int nthUglyNumber(int n) {
    
    
        if (n==1) return 1;
        vector<int> x(n+1);
        x[1]=1;
        int a=1,b=1,c=1;
        for (int i=2;i<=n;i++){
    
    
            x[i]=min(x[a]*2,min(x[b]*3,x[c]*5));
            if (x[i]==x[a]*2) a++;
            if (x[i]==x[b]*3) b++;
            if (x[i]==x[c]*5) c++;
        }
        return x[n];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_34600424/article/details/107676264