classSolution: defnthMagicalNumber(self, n: int, a: int, b: int) -> int: MOD = 10 ** 9 + 7 c = lcm(a, b) m = c // a + c // b - 1 r = n % m res = c * (n // m) % MOD if r == 0: return res addA = a addB = b for _ inrange(r - 1): if addA < addB: addA += a else: addB += b return (res + min(addA, addB) % MOD) % MOD
二分查找
这个二分确实不看题解没想过,榆木脑袋是这样的呜呜
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defnthMagicalNumber(self, n: int, a: int, b: int) -> int: MOD = 10 ** 9 + 7 l = min(a, b) r = n * min(a, b) c = lcm(a, b) while l <= r: mid = (l + r) // 2 cnt = mid // a + mid // b - mid // c if cnt >= n: r = mid - 1 else: l = mid + 1 return (r + 1) % MOD