Ugly Number

127 篇文章 0 订阅

Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解析:

代码:

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int>index(3,0);
        
        vector<int>ugly(n,INT_MAX);
        if (n==1) return 1;
        ugly[0]=1;
        vector<int>base(3,0);
        base[0]=2;
        base[1]=3;
        base[2]=5;
        for (int i=1; i<n; i++)
        {
            for (int j=0; j<3; j++)
            {
                ugly[i]=min(ugly[i],ugly[index[j]]*base[j]);
            }
            for (int j=0; j<3; j++)
            {
                while (ugly[index[j]]*base[j]<=ugly[i])
                index[j]++;
            }
        }
        
        return ugly[n-1];
    }
};

Super Ugly Number

Write a program to find the nth super ugly number.

Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.

Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
(4) The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

解析:

ugly[i]为第i个丑数,把得到的第一个乘以2后大于M的结果记为M2,同样把已有的每个丑数乘以3和5,得到第一个大于M的结果即为M3和M5,那么下一个丑数为M2,M3,M5这三个数中的最小者,因为所有丑数都是按顺序存放在数组中的,对乘以2而言,肯定存在一个某个丑数T2,排在他之前的每个丑数乘以2得到的结果都会小于已有的最大丑数,在他之后的每一个丑数乘以2得到的结果都会太大,我们只需记住这个丑数的位置,每次生成新的丑数时更新这个T2,同样对于其他的质数也存在同样的T3,T5等,把这个数组记录为index[].

代码:

class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        if (n==1) return 1;
        
        int primesnum=primes.size();
        vector<int>index(primesnum,0);
        vector<int>ugly(n,INT_MAX);
        ugly[0]=1;
        for (int i=1; i<n; i++)
        {
            for (int j=0; j<primesnum; j++)
            {
                ugly[i]=min(ugly[i],ugly[index[j]]*primes[j]);
            }
            for (int j=0; j<primesnum; j++)
            {
                while((ugly[index[j]]*primes[j])<=ugly[i])
                index[j]++;
            }
        }
        return ugly[n-1];
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值