A sorted list A
contains 1, plus some number of primes. Then, for every p < q in the list, we consider the fraction p/q.
What is the K
-th smallest fraction considered? Return your answer as an array of ints, where answer[0] = p
and answer[1] = q
.
Examples: Input: A = [1, 2, 3, 5], K = 3 Output: [2, 5] Explanation: The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, 2/3. The third fraction is 2/5. Input: A = [1, 7], K = 1 Output: [1, 7]
Note:
A
will have length between2
and2000
.- Each
A[i]
will be between1
and30000
. K
will be between1
andA.length * (A.length - 1) / 2
.
class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& A, int K)
{
double left=0,right=1;
double mid;
int count = 0;
int n = A.size();
int p=0,q=1;
while(1)
{
mid =(left+right)/2;
count = 0;
p = 0;
for(int i = 0;i<n-1;i++)
{
int j = i+1;
while(j<n && A[i]>mid*A[j]){j++;}
count += n-j;
if(j<n && p*A[j]<q*A[i])
{
p = A[i];
q = A[j];
}
}
if(count< K ) left = mid;
else if(count == K) return {p,q};
else right = mid;
}
}
};