-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0786-k-th-smallest-prime-fraction.js
53 lines (46 loc) · 1.24 KB
/
0786-k-th-smallest-prime-fraction.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 786. K-th Smallest Prime Fraction
* https://leetcode.com/problems/k-th-smallest-prime-fraction/
* Difficulty: Medium
*
* You are given a sorted integer array arr containing 1 and prime numbers, where all the integers
* of arr are unique. You are also given an integer k.
*
* For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
*
* Return the kth smallest fraction considered. Return your answer as an array of integers of size
* 2, where answer[0] == arr[i] and answer[1] == arr[j].
*/
/**
* @param {number[]} arr
* @param {number} k
* @return {number[]}
*/
var kthSmallestPrimeFraction = function(arr, k) {
const n = arr.length;
let left = 0;
let right = 1;
while (left < right) {
const mid = (left + right) / 2;
let count = 0;
let maxFraction = [0, 1];
let j = 1;
for (let i = 0; i < n - 1; i++) {
while (j < n && arr[i] > mid * arr[j]) {
j++;
}
count += n - j;
if (j < n && arr[i] * maxFraction[1] > maxFraction[0] * arr[j]) {
maxFraction = [arr[i], arr[j]];
}
}
if (count === k) {
return maxFraction;
} else if (count < k) {
left = mid;
} else {
right = mid;
}
}
return [];
};