1508. Kth Smallest Ratio
A lab keeps n positive sample weights in nums, already sorted in non-decreasing order. For every pair of positions i < j it forms the ratio nums[i] / nums[j], which is at most 1. Equal ratios from different pairs are all kept, so there are exactly n(n - 1) / 2 ratios counted with multiplicity.
Return the k-th smallest of these ratios (k is 1-based) as an array [p, q] holding the fraction in lowest terms, so p / q is that ratio and gcd(p, q) = 1. Hint: binary search a bound on the ratio; for each bound count the pairs not exceeding it with two pointers, while tracking the largest such fraction by exact cross-multiplication, and reduce it by the gcd at the end. Different fractions with weights up to 30000 differ by at least 1e-9, so a grid of that fineness is enough. Aim for O(n log C) time and O(1) extra space.
Example 1
- Input:
- nums = [1,2,3,6], k = 3
- Output:
- [1,3]
- Explanation:
The six ratios in order are 1/6, 1/3, 1/3, 1/2, 1/2 and 2/3, so the third smallest is 1/3.
Example 2
- Input:
- nums = [4,4], k = 1
- Output:
- [1,1]
- Explanation:
There is only one pair and its ratio is 4/4, which reduces to 1/1.
Example 3
- Input:
- nums = [2,3,5], k = 2
- Output:
- [3,5]
- Explanation:
The ratios in order are 2/5, 3/5 and 2/3, so the second smallest is 3/5.
Constraints
2 ≤ n ≤ 105
1 ≤ nums[i] ≤ 3 * 104, nums sorted non-decreasing
1 ≤ k ≤ n(n - 1) / 2
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log C)
- Space
- O(1)