K-th Smallest Prime Fraction

You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.

For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].

Return the kth the smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].

Example:

Input: arr = [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, and 2/3.
The third fraction is 2/5.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

class compare
{
public:
    bool operator()(pair<doublepair<intint>> a
pair<doublepair<intint>> b)
    {
        return a.first > b.first;
    }
};

vector<intkthSmallestPrimeFraction(vector<int&Aint K)
{
    priority_queue<pair<doublepair<intint>>, 
vector<pair<doublepair<intint>>>, comparepq;
    int n = A.size();
    for (int i = 1i < A.size(); ++i)
    {
        pq.push({(A[0] * 1.0 / A[i] * 1.0), {0i}});
    }
    pair<doublepair<intint>> p;
    while (K > 0)
    {
        p = pq.top();
        pq.pop();
        if (p.second.first + 1 < p.second.second)
        {
            pq.push({(A[p.second.first + 1] * 1.0 / 
A[p.second.second] * 1.0), 
{p.second.first + 1p.second.second}});
        }
        K--;
    }
    vector<intres = {A[p.second.first]A[p.second.second]};
    return res;
}

int main()
{
    vector<intarr = {1235};
    int k = 3;

    vector<intres = kthSmallestPrimeFraction(arrk);

    cout << "[";

    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment