题目:
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
.A[i]
will be between 1
and 30000
.K
will be between 1
and A.length * (A.length - 1) / 2
.思路:
1、优先队列:
我们先找规律,观察题目中给出的的例子[1, 2, 3, 5],很容易知道:
1/5 < 1/3 < 1/2
2/5 < 2/3
3/5
也就是说,对于每个A[i],如果以它为分子,则分母从A.back()到A[i+1],与A[i]构成的分数呈严格递增序列。在这种情况下,我们可以通过优先队列来依次取出K个数,那么其取出的第K个数,就是我们所求。我们定义一个priority_queue
在实现中,为了保证最小的值首先被从pq中取出,我们将分数取负作为优先队列中的key。算法的空间复杂度为O(n),时间复杂度为O(Klogn)。
2、二分查找:
上面这个算法的问题在于当K特别大的时候,算法的时间复杂度其实还挺高的。另外一种解决思路就是采用二分查找。还是以题目中给出的[1,2,3,5]为例俩说明问题:
我们初始化left = 0, right = 1,作为二分查找的边界。然后每次取left和right的中间值,再分别计算每行中有多少个值小于等于mid。最后将所有行中小于等于mid的分数的个数加起来,记为count。如果发现count小于K,那么说明mid的取值过小,所以修改左边界;否则修改右边界。这样当count的个数刚好为K的时候,我们取小于等于mid的所有分数中的最大值,即为第K大的分数。二分查找法的空间复杂度为O(1),时间复杂度为O(log(r)n^2),其中r是left和right之间的差值。可以发现这个算法的时间复杂度与K无关。由于K一般情况下下是O(n^2)量级的,所以二分查找的时间复杂度还是要好于基于优先队列的方法。
代码:
1、优先队列:
class Solution {
public:
vector kthSmallestPrimeFraction(vector& A, int K) {
priority_queue>> pq;
for(int i = 0; i < A.size(); ++i) {
pq.push({-1.0 * A[i] / A.back(), {i, A.size()-1}});
}
while(--K > 0) {
pair cur = pq.top().second;
pq.pop();
if (--cur.second > cur.first) {
pq.push({-1.0 * A[cur.first] / A[cur.second], {cur.first, cur.second}});
}
}
return {A[pq.top().second.first], A[pq.top().second.second]};
}
};
2、二分查找:
class Solution {
public:
vector kthSmallestPrimeFraction(vector& A, int K) {
double left = 0, right = 1;
int p = 0, q = 1, count = 0;
while (true) {
count = 0, p = 0;
double mid = (left + right) / 2;
// using A[i] as the numerator, and A[n - 1 - j] denominator
for (int i = 0; i < n; ++i) {
int j = n - 1;
// find the first A[n - 1 - j] that A[i] / A[n - 1 - j] <= mid
while (j >= 0 && A[i] > mid * A[n - 1 - j]) {
--j;
}
count += (j + 1);
// update p and q if A[i] / A[n - 1 - j] is larger than p / q
if (j >= 0 && p * A[n - 1 - j] < q * A[i]) {
p = A[i];
q = A[n - 1 - j];
}
}
if (count < K) {
left = mid;
} else if (count > K) {
right = mid;
} else {
return {p, q};
}
}
return {p, q};
}
};