leetcode 786. K-th Smallest Prime Fraction

探讨一种算法,用于从包含1和其他若干素数的列表中找出第K小的比例p/q,其中p和q均为列表中的素数,并提供了一个具体的实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
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;
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值