Advertisement
serega1112

786 binary search

Dec 18th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. class Solution:
  2.     def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]:
  3.         low = A[0] / A[-1]
  4.         high = 1
  5.         res = 0
  6.        
  7.         def less_than_or_eq_k(x):
  8.             count = 0
  9.             p_best = None
  10.             q_best = None
  11.             l = -1
  12.             r = 1
  13.             while r < len(A):
  14.                 while A[l+1] <= A[r] * x:
  15.                     l += 1
  16.                 count += l + 1
  17.                 if l >= 0:
  18.                     if p_best is None or A[p_best] / A[q_best] < A[l] / A[r]:
  19.                         p_best = l
  20.                         q_best = r
  21.                 r += 1
  22.             return count, p_best, q_best
  23.        
  24.         while high - low > 1e-07:
  25.             mid = low + (high - low) / 2.0
  26.             count, p, q = less_than_or_eq_k(mid)
  27.             if count > K:
  28.                 high = mid
  29.             else:
  30.                 low = mid
  31.                 res = (A[p], A[q])
  32.                
  33.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement