LC.P1201[丑数III]

方法一:容斥原理+二分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int nthUglyNumber(int n, int a, int b, int c) {
long ab = lcm(a, b), ac = lcm(a, c), bc = lcm(b, c), abc = lcm(a, lcm(b, c));
long left = 0, right = (long) Math.min(a, Math.min(b, c)) * n;
while (left < right) {
long mid = left + right >> 1;
if (mid / a + mid / b + mid / c - mid / ab - mid / ac - mid / bc + mid / abc >= n) right = mid;
else left = mid + 1;
}
return (int) right;
}

// 最小公倍数
private long lcm(long a, long b) {
return a * b / gcd(a, b);
}

// 最大公约数
private long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}
  • 时间复杂度:$O(log(min(a,b,c) \times n))$
  • 空间复杂度:$O(1)$