LeetCode 786. K-th Smallest Prime Fraction

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hzh_0000/article/details/79388787

题意

有一个由1和质数组成的序列,对于序列中的任意p,q,若p

题解

数列长度是3000,所以最多也就10^6个分数,快排一下复杂度应该够的。但是这题应该是卡常数了。快排复杂度是 N 2 l o g N 2 ,N是数列长度,也就是 2 N 2 l o g N
对于数列[1,2,3,5],我们考虑:

1/2
1/3 2/3
1/5 2/5 3/5

所以每次我们只把第一列的加入一个优先队列,然后每次取出最小的更新队列,这样只需要操作K次就行了。
那么复杂度就是 N 2 l o g N ,因为队列长度是N,所以少了常数2.

代码

struct Node {
    int pos1, pos2;
    int p, q;
    bool operator<(const Node & b) const {
        return p * b.q > q * b.p;
    }
};


class Solution {
public:

    vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
        priority_queue<Node> q;
        for (int i = 1; i < A.size(); i++) {
            Node node;
            node.pos1 = 0;
            node.pos2 = i;
            node.p = A[node.pos1];
            node.q = A[node.pos2];
            q.push(node);
        }
        vector<int> ans = { 0, 0 };
        while (K--) {
            Node temp = q.top();
            // cout << temp.p << temp.q << endl;
            q.pop();
            if (!K) {
                ans[0] = temp.p;
                ans[1] = temp.q;
            }
            if (temp.pos1 >= temp.pos2) {
                continue;
            }
            temp.pos1++;
            temp.p = A[temp.pos1];
            q.push(temp);
        }

        return ans;
    }


};

猜你喜欢

转载自blog.csdn.net/hzh_0000/article/details/79388787
今日推荐