Skip to content

Commit 742c6ab

Browse files
committed
786
1 parent 984d853 commit 742c6ab

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

BS/786.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## K-th Smallest Prime Fraction
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/k-th-smallest-prime-fraction/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code 2
16+
17+
O(log(n))
18+
19+
```python
20+
class Solution:
21+
'''
22+
思路:
23+
1. 所有在A[i]/m右边的数字A[j],代表A[i]/A[j]都小于m
24+
2. 将所有这些数字加起来(cur),可以得到所有A[i]/A[j]<m的数字总和
25+
3. 当这个数字恰好等于k的时候,找到最大的数字即是答案
26+
'''
27+
def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]:
28+
l, r, N = 0, 1, len(A)
29+
while True:
30+
m = (l + r) / 2
31+
border = [bisect.bisect(A, A[i] / m) for i in range(N)]
32+
cur = sum(N - i for i in border)
33+
if cur > K:
34+
r = m
35+
elif cur < K:
36+
l = m
37+
else:
38+
return max([(A[i], A[j]) for i, j in enumerate(border) if j < N], key=lambda x: x[0] / x[1])
39+
```

0 commit comments

Comments
 (0)