786. K-th Smallest Prime Fraction

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 between 2 and 2000.
  • Each A[i] will be between 1 and 30000.
  • K will be between 1 and A.length * (A.length - 1) / 2.

 
 
 1 struct lessPair{
 2     bool operator()(pair<int,int>&p1, pair<int,int>&p2){
 3         return (p1.first*1.0/p1.second)<(p2.first*1.0/p2.second); //interger devision needs to convert to float
 4     }
 5 };
 6 class Solution {
 7 public:
 8     vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
 9         sort(A.begin(),A.end());
10         priority_queue<pair<int,int>,vector<pair<int,int>>,lessPair> pq; //max-heap
11         for(int i=0;(i<K)&&(i<A.size());i++){
12             for(int j=A.size()-1;(j>i)&&(A.size()-j<=K);j--){ //be careful on the boundary!!!
13                 if(pq.size()<K){
14                     pq.push(make_pair(A[i],A[j]));
15                 }else{
16                     if((A[i]*1.0/A[j])<(pq.top().first*1.0/pq.top().second)){
17                         pq.pop();
18                         pq.push(make_pair(A[i],A[j]));
19                     }
20                 }
21             }
22         }
23         vector<int> result;
24         result.push_back(pq.top().first);
25         result.push_back(pq.top().second);
26         return result;
27     }
28     
29 };

 

posted @ 2018-07-11 21:22  回到明天  阅读(75)  评论(0)    收藏  举报