leetcode--1201. 丑数 III

题目:1201. 丑数 III

链接:https://leetcode-cn.com/problems/ugly-number-iii/

这个题目我没做出来,有个知识点不知道,看完评论之后才懂:

n以内的丑数个数为 n / a + n / b + n / c - n / lcm(a, b) - n / lcm(a, c) - n / lcm(b, c) + n / lcm(a, b, c),在这个基础上就比较容易想到二分查找了

C++:

typedef long long LL;

class Solution {
public:
    LL gcd(LL a, LL b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    int nthUglyNumber(int n, int a, int b, int c) {
        LL gcd_ab = gcd(a, b), gcd_bc = gcd(b, c), gcd_ac = gcd(a, c);
        LL lcm_ab = static_cast(1.0 * a * b / gcd_ab), lcm_ac = static_cast(1.0 * a * c / gcd_ac), 
        lcm_bc = static_cast(1.0 * b * c / gcd_bc);
        LL lcm_abc = lcm_ab * c / gcd(lcm_ab, c);
        LL left = 1, right = static_cast(2e9 + 1);
        while (left <= right) {
            LL mid = (left + right) / 2;
            LL cnt = mid / a + mid / b + mid / c - mid / lcm_ab - mid / lcm_ac - mid / lcm_bc + mid / lcm_abc;
            if (cnt < n) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return static_cast(left);
    }
};

评论里面还有老哥说,C++17已经在里定义了最大公约数std::gcd和最小公倍数std::lcm啦,敲黑板划重点,记住,要考的!

你可能感兴趣的:(leetcode)