786. K-th Smallest Prime Fraction #174
-
|
Topics: You are given a sorted integer array For every Return the Example 1:
Example 2:
Constraints:
Follow up: Can you solve the problem with better than |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
Here is a detailed breakdown: Approach:
Let's implement this solution in PHP: 786. K-th Smallest Prime Fraction <?php
/**
* @param Integer[] $arr
* @param Integer $k
* @return Integer[]
*/
function kthSmallestPrimeFraction($arr, $k) {
$n = count($arr);
$l = 0.0;
$r = 1.0;
while ($l < $r) {
$m = ($l + $r) / 2.0; // Midpoint in binary search
$fractionsNoGreaterThanM = 0; // Count of fractions <= m
$p = 0; // Numerator of the closest fraction
$q = 1; // Denominator of the closest fraction
// Two pointers for each fraction arr[i] / arr[j]
for ($i = 0, $j = 1; $i < $n; ++$i) {
// Move j while the fraction arr[i] / arr[j] > m
while ($j < $n && $arr[$i] > $m * $arr[$j]) {
++$j;
}
// If we reach the end of the array, break out of the loop
if ($j == $n) {
break;
}
// Count fractions with arr[i] / arr[j] <= m
$fractionsNoGreaterThanM += $n - $j;
// Track the largest fraction <= m
if ($p * $arr[$j] < $q * $arr[$i]) {
$p = $arr[$i];
$q = $arr[$j];
}
}
// Check if the count matches k
if ($fractionsNoGreaterThanM == $k) {
return [$p, $q]; // Return the k-th smallest fraction
}
// Adjust the binary search bounds
if ($fractionsNoGreaterThanM > $k) {
$r = $m; // Too many fractions, search left side
} else {
$l = $m; // Too few fractions, search right side
}
}
throw new Exception("Kth smallest prime fraction not found.");
}
// Example 1:
$arr1 = [1, 2, 3, 5];
$k1 = 3;
$result1 = kthSmallestPrimeFraction($arr1, $k1);
echo "[" . implode(", ", $result1) . "]\n"; // Output: [2, 5]
// Example 2:
$arr2 = [1, 7];
$k2 = 1;
$result2 = kthSmallestPrimeFraction($arr2, $k2);
echo "[" . implode(", ", $result2) . "]\n"; // Output: [1, 7]
?>Explanation:
Time Complexity:
Thus, the total time complexity is approximately O(n log(precision)), where n is the length of the array and the precision is determined by how accurately we search for the midpoint. This is better than the brute-force O(n2) approach. |
Beta Was this translation helpful? Give feedback.
Here is a detailed breakdown:
Approach:
Binary Search on Fractions:
We perform a binary search over the range of possible fraction values, starting from
0.0to1.0. For each midpointm, we count how many fractions are less than or equal tomand track the largest fraction in that range.Counting Fractions:
Using two pointers, for each prime
arr[i], we find the smallestarr[j]such thatarr[i] / arr[j]is greater than the current midpointm. We keep track of the number of valid fractions found and update the fraction closest tombut smaller thanm.Binary Search Adjustments:
If the number of fractions less than or equal to
mis exactlyk, we return the best fraction found so far. If…