Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2513. Minimize the Maximum of Two Arrays #175

Open
Woodyiiiiiii opened this issue Jan 12, 2023 · 0 comments
Open

Leetcode 2513. Minimize the Maximum of Two Arrays #175

Woodyiiiiiii opened this issue Jan 12, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jan 12, 2023

这道题也是经典的二分法。

难点在check函数上,如何计算不同的数。

这时候要用到数学了,用集合相交的思想,中间重叠的部分是能被公倍数整除的个数。

计算uniqueCnt1 + uniqueCnt2 <= mid - mid / lcm是检验divisor1=divisor2的情况。

class Solution {
    public int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) {
        long lo = 2, hi = (int) (2 * 1e9);
        long lcm = (long) divisor1 * divisor2 / gcd(divisor1, divisor2);
        while (lo < hi) {
            long mid = (lo + hi) >> 1;
            if (uniqueCnt1 <= mid - mid / divisor1 && uniqueCnt2 <= mid - mid / divisor2 && uniqueCnt1 + uniqueCnt2 <= mid - mid / lcm) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        return (int) lo;
    }

    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant