1201. Ugly Number III && 264. Ugly Number ll

First, we can enumerate different numbers as a candidate answer as long as there are n - 1's ugly numbers before it.

So, right now we have three conditions here, the first one is all the ugly numbers should be smaller than the answer. The second condition is all the ugly numbers should be divisible by a, b, c. The third condition is there are total of n - 1's ugly numbers before answer.

THe first condition is easy to solve.

The second condition is easy to solve too.

The only annoying condition is the last condition. How to count how many ugly number are smaller than the current number?

for example, we have 3 6 9 12

let say a is 3.

how many ugly number that is divisible by 3 and smaller than 12? the answer is 12/ 3.

as 6 9 12 are all the multiple of 3, we can ensure how many times 3 is able to multiply itself.

But there are a, b, c, there will occur some duplicate cases.

ans/a + ans/b + ans/c - ans/lcm(a,b) - ans/lcm(a,c) - ans/lcm(b, c) + ans/lcm(a,b,c)

typedef long long ll;
class Solution {
public:
    ll gcd(ll a, ll b){
        if(!b)return a;
        return gcd(b, a % b);
    }
    ll lcm(ll a, ll b){
        return a * b / gcd(a, b);
    }
    ll lcm2(ll a, ll b, ll z){
        int res = lcm(a, b);
        return lcm(res, z);
    }
    ll nthUglyNumber(int n, int a, int b, int c) {
        ll l = 0, r = INT_MAX;
        while(l <= r){
            ll mid = (l + r) / 2;
            ll cnt = mid/a + mid/b + mid/c - mid/(lcm(a,b)) - mid/(lcm(a,c)) - mid/(lcm(b,c)) + mid/lcm2(a,b,c); 
            if(cnt < n){
                l = mid + 1;
            }else{
                r = mid - 1;
            }
        }
        return l;
    }
};

264. Ugly Number ll

Every time, we generate a new number by multiplying a number by 2/ 3/ 5, we will always make sure the number is minimum, and if we used a 2/3/5, we have to increase the pointer by 1, it will naturally create a sorted array which all the number only have 2/3/5 factors.

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> v(n + 1, 1);
        int t1 = 0, t2 = 0, t3 = 0;
        for(int i = 1; i <= n; i++){
            v[i] = min(v[t1]*2, min(v[t2]*3, v[t3]*5));
            if(v[i] == v[t1]*2) t1++;
            if(v[i] == v[t2]*3) t2++;
            if(v[i] == v[t3]*5) t3++;
        }
        return v[n - 1];
        
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值