题目大意:给你一些互质数字,求出它们组成的分数中第K小的分数。
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
.
1 2 3 4 5 6 7 8 9 10 |
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 between2
and2000
.- Each
A[i]
will be between1
and30000
. K
will be between1
andA.length * (A.length + 1) / 2
.
Solution 1: Binary Search
Binary search m, 0 < m < 1, such that there are exact k pairs of (i, j) that A[i] / A[j] < m
Time complexity: O(n*C) C <= 31
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Author: Huahua // Running time: 13 ms class Solution { public: vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) { const int n = A.size(); double l = 0; double r = 1.0; while (l < r) { double m = (l + r) / 2; double max_f = 0.0; int total = 0; int p, q = 0; for (int i = 0, j = 1; i < n - 1; ++i) { while (j < n && A[i] > m * A[j]) ++j; if (n == j) break; total += (n - j); const double f = static_cast<double>(A[i]) / A[j]; if (f > max_f) { p = i; q = j; max_f = f; } } if (total == K) return {A[p], A[q]}; else if (total > K) r = m; else l = m; } return {}; } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Author: Huahua // Running time: 16 ms class Solution { public int[] kthSmallestPrimeFraction(int[] A, int K) { final int n = A.length; double l = 0; double r = 1.0; while (l < r) { double m = (l + r) / 2; double max_f = 0.0; int total = 0; int p = 0; int q = 0; for (int i = 0, j = 1; i < n - 1; ++i) { while (j < n && A[i] > m * A[j]) ++j; if (n == j) break; total += (n - j); final double f = (double)A[i] / A[j]; if (f > max_f) { p = i; q = j; max_f = f; } } if (total == K) return new int[]{A[p], A[q]}; else if (total > K) r = m; else l = m; } return new int[] {}; } } |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
""" Author: Huahua Running time: 172 ms """ class Solution: def kthSmallestPrimeFraction(self, A, K): n = len(A) l = 0.0 r = 1.0 while l < r: m = (l + r) / 2 max_f = 0.0 total = 0 j = 1 for i in range(n - 1): while j < n and A[i] > m * A[j]: j += 1 if j == n: break total += n - j f = A[i] / A[j] if f > max_f: p, q, max_f = i, j, f if total == K: return [A[p], A[q]] elif total > K: r = m else: l = m return [] |
Related Problems:
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment