LeetCode|Ugly Number*

Ugly Number

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

class Solution {
public:
    bool isUgly(int num) {
        if(num < 1) return false;
        while((num & 1) == 0) num >>= 1;
        while(num % 3 == 0) num /= 3;
        while(num % 5 == 0) num /= 5;
        return num == 1;
    }
};

这里去掉括号竟然会WA,难道 == 的优先级要高于 & ?

while((num & 1) == 0) num >>= 1;

Ugly Number II

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.

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:

  • 1 is typically treated as an ugly number.
  • n does not exceed 1690.

《剑指offer》上也有丑数这道题。

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> v(1700, 1);  // 这里得写常数
        v[1] = 2;
        v[2] = 3;
        v[3] = 4;
        v[4] = 5;
        int p2 = 0, p3 = 0, p5 = 0;
        for(int i = 4; i < n-1; ++i){
            while(v[p2]*2 <= v[i]) ++p2;
            while(v[p3]*3 <= v[i]) ++p3;
            while(v[p5]*5 <= v[i]) ++p5;
            v[i+1] = min(min(v[p2]*2, v[p3]*3), v[p5]*5);
        } return v[n-1];
    }
};

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.

Example:

Input: n = 12, primes = [2,7,13,19]
Output: 32 
Explanation: [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 is a super ugly number for any given primes.
  • The given numbers in primes are in ascending order.
  • 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
  • The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

下面这份代码的时间复杂度为 O(nklogk)… 明显还可以优化

class Solution {
public:
    Solution(){
        v[0] = 1;
    }
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> pv(primes.size(), 0);
        set<int> s;
        for(int i = 0, e = n-1; i < e; ++i){
            for(int j = 0; j < primes.size(); ++j){
                while(v[pv[j]]*primes[j] <= v[i]) ++pv[j];
                s.insert(v[pv[j]]*primes[j]);
            } v[i+1] = *(s.begin());
            s.erase(s.begin());
        } return v[n-1];
    }
private:
    int v[1000000];
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值